简体   繁体   中英

How to query mongo db by _id?

I am using MongoDB with Spring. I want to query the database by _id.

Currently I have this query:

Query q = new Query(Criteria.where("_id").is(someId).and("deleted").is(false));

But this is giving me StackOverflowError somehow. What's wrong with this query? Or what is a better way of doing this?

Create an explicit AND query instead of a chained one using the $and operator Criteria.andOperator() for all of the provided criteria as follows:

Query q = new Query(
    new Criteria().andOperator(
        Criteria.where("_id").is(someId),
        Criteria.where("deleted").is("false")
    )
);

This is normally used in instances where you can't use Criteria.and() to add multiple criteria into the same field, for example

Query q = new Query();
q.addCriteria(Criteria.where("age").lt(40).and("age").gt(10));

will throw an error, so a workaround would be to use Criteria.andOperator() as

Query q = new Query();
q.addCriteria(
    Criteria.where("age").exists(true).andOperator(
        Criteria.where("age").gt(10),
        Criteria.where("age").lt(40)
    )
);

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