import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
public class MongoDB {
private static MongoClient client;
private static DBCollection collection;
public static void main(String[] args) throws IOException {
createCollection();
collection.ensureIndex(new BasicDBObject("a", 1).append("b", -1)
.append("c", 1));
BasicDBObject query = new BasicDBObject("a", 40000).append("b", 40000)
.append("c", 40000);
DBObject document = collection.find(query).hint("a_1_b_-1_c_1")
.explain();
printExplain(document);
// or
BasicDBObject hint = new BasicDBObject("a", 1).append("b", -1).append(
"c", 1);
DBObject document2 = collection.find(query).hint(hint).explain();
printExplain(document2);
client.close();
}
private static void printExplain(DBObject document) {
Set<String> keySet = document.keySet();
for (String str : keySet) {
System.out.printf("%25s:%s\n", str, document.get(str));
}
}
private static void createCollection() throws UnknownHostException {
client = new MongoClient(new ServerAddress("localhost", 27017));
DB database = client.getDB("databaseName");
collection = database.getCollection("collectionName");
}
}