spring data mongo - mongotemplate count with query hint

anztenney picture anztenney · Oct 29, 2014 · Viewed 14k times · Source

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.

Answer

Neil Lunn picture Neil Lunn · Oct 29, 2014

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.