2

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.

Hermann Hans
  • 1,798
  • 1
  • 13
  • 24
Rajith Delantha
  • 713
  • 11
  • 21

1 Answers1

4

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);
cubbuk
  • 7,800
  • 4
  • 35
  • 62