5

The mongo docs specify that you can specify a query hint for count queries using the following syntax:

db.orders.find(
   { ord_dt: { $gt: new Date('01/01/2012') }, status: "D" }
).hint( { status: 1 } ).count()

Can you do this using the mongo template? I have a Query object and am calling the withHint method. I then call mongoTemplate.count(query); However, I'm pretty sure it's not using the hint, though I'm not positive.

0

1 Answer 1

3

Sure, there are a few forms of this including going down to the basic driver, but assuming using your defined classes you can do:

    Date date = new DateTime(2012,1,1,0,0).toDate();
    Query query = new Query();
    query.addCriteria(Criteria.where("ord_dt").gte(date));
    query.addCriteria(Criteria.where("status").is("D"));
    query.withHint("status_1");

    long count = mongoOperation.count(query, Class);

So you basically build up a Query object and use that object passed to your operation, which is .count() in this case.

The "hint" here is the name of the index as a "string" name of the index to use on the collection. Probably something like "status_1" by default, but whatever the actual name is given.

Sign up to request clarification or add additional context in comments.

4 Comments

Actually this doesn't seem to use the hint. I have set the query.withHint using an index name that does not exist in the db. If I run the query like this: mongoTemplate.find(query, Class).size() It blows up with the error planner returned error: bad hint, but if I run mongoTemplate.count(query, Class) it works fine. Maybe count doesn't use the planner, but to me it seems like it's not working.
@anztenney Well it was pretty clearly stated that you need to set the hint to the name of an index that exists on the collection. So you are doing it wrong.
What I'm trying to say is that it doesn't look like the hint is actually working properly when using count. I agree that I should send a valid hint name, but how can I verify the hint is really being sent?
@anztenney Umm, well you can mess around with inspecting explain output. But the method shown is how you specify a "hint" to a Query object for spring-mongodb. It just calls the underlying driver method to do the same. I was going to point out originally that you should reverse the order of arguments to "help" the query optimizer understand what you mean without "forcing" the "hint" in the first place. Generally the optimizer should "sort it out" given which choice produces the "least matches", which means "optimal".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.