'How to provide a hint in java-mongodb driver for find

I am trying to tune some queries I have on my mongodb from a java client. Inspecting the active running operations for the current database I noticed the fact that some queries having something like:

db.getCollection("buba-collection").find({ _id: { $in: [ "aaaa", "bbb", "cccc"  } });

they are not touching any index. It is true, I may have up to 1k elements in $in clause, but only 15-20% of the queries are not touching the index. The mongo-cluster is sharded (hash, by _id) and I am looking to get elements via _id_ index or by the sharded index. They should provide the same performance - I guess. The expected result should be:

db.getCollection("buba-collection").find({ _id: { $in: [ "aaaa", "bbb", "cccc"  } }).hint("sharded_index");

So, what I tried:

MongoCollection<Document> source = getCollectionHere();
BasicDBList docIds = new BasicDBList();
docIds.addAll(ids);
BasicDBObject inClause = new BasicDBObject("$in", docIds);
BasicDBObject query = new BasicDBObject("_id", inClause);
return source.find(query).batchSize(1000).hint(new BasicDBObject("_id", 1)).iterator();

It seems like the only possible way is to provide the indexed column I am after. However, in mongodb docs they mention that you can also specify the index name.

My question is: can I do the same thing in Java?

Mongodb version: 4.0.3;
Java driver version: 3.10.1;
Java: 1.8.200;


Solution 1:[1]

you should specify field name , not the index name.like this:

return source.find(query).batchSize(1000).hint(new BasicDBObject("field_name", 1)).iterator();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shuimuzi