简体   繁体   中英

Convert MongoDB query into Java

I need to convert the following mongo query into java.

db.sample.find( { name:"abc" }, { _id: 0, cities: { $elemMatch: { cityName: "A" }}});

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

    BasicDBObject eleMatch = new BasicDBObject();
    eleMatch.put("cityName","A");
    BasicDBObject up = new BasicDBObject();
    up.put("$elemMatch",eleMatch);
    BasicDBObject query = new BasicDBObject();
    query.put("name","abc");
    query.put("cities",up);
    DBCollection dbcoll = mongoTemplate.getCollection("sample");
    DBObject object = dbcoll.findOne(query);

But the result of this object contains the id . So i just need to get rid of that.

You need to give retrieved fields as the second parameter of findOne method

BasicDBObject retrievedField = new BasicDBObject();
retrievedField.put("_id",0);

dbcoll.findOne(query, retrievedField);

Also if you want to retrieve the exact query you shown I think you need to append elemMatch object to retrievedFields instead of adding it to queryObject.

BasicDBObject eleMatch = new BasicDBObject();
eleMatch.put("cityName","A");
BasicDBObject up = new BasicDBObject();
up.put("$elemMatch",eleMatch);
retrievedField.append(up);

BasicDBObject query = new BasicDBObject();
query.put("name","abc");

DBCollection dbcoll = mongoTemplate.getCollection("sample");
DBObject object = dbcoll.findOne(query, retrievedField);

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