简体   繁体   中英

spring data mongo - mongotemplate count with query hint

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM