how to convert MongoDB query into Java

I need to convert the following mongo query into java with spring-data-mongodb.

db.getCollection('test').find({ '_id' : 15},{'viewList':{'$elemMatch':{'essayId':14}}})

I tried so many ways but I couldn't figure out the correct way.

Criteria findModelCriteria = Criteria.where("id").is(15);
Criteria findFuelCriteria = Criteria.where("viewList").elemMatch(Criteria.where("essayId").is(14));
BasicQuery basicQuery = new BasicQuery(findModelCriteria.getCriteriaObject(), findFuelCriteria.getCriteriaObject());

1 answer

  • answered 2017-10-11 10:03 barbakini

    As said in comment, you should use_id not id. Plus, you don't need BasicQuery. You can use Query with MongoTemplate like that:

    @Autowired
    private MongoTemplate mongoTemplate;
    ....
    
    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(15));
    query.addCriteria(Criteria.where("viewList").elemMatch(Criteria.where("essayId").is(14)));
    List<YourClass> list = mongoTemplate.find(query, YourClass.class);