3

In mongodb version 3 using java api how do we give a hint while querying The query result is FindIterable which has MongoCursor. How should I give a hint to use a particular index.

With older versions there is DBCursor which have API's for hint.

Devesh
  • 191
  • 1
  • 5

2 Answers2

2

modifiers should be used:

BasicDBObject index = new BasicDBObject("num", 1);
BasicDBObject hint = new BasicDBObject("$hint", index);
FindIterable<Document> iterable = collection.find().modifiers(hint);
Alvin
  • 31
  • 5
1

You need to use FindIterable.modifiers method to specify $hint:

private static void testHint(MongoDatabase db) {
    MongoCollection<Document> col = db.getCollection("Stores");
    FindIterable<Document> iterable = col.find(new Document("store","storenumbervalue"));
    iterable.modifiers(new Document("$hint","index_name"));
    MongoCursor curs =  iterable.iterator();
    while(curs.hasNext()){
        System.out.println(curs.next());
    }        
}

index_name - actual index name in mongo.

vad
  • 47
  • 3