将MongoDB查询转换为Java

时间:2013-01-25 11:20:41

标签: java mongodb

我需要将以下mongo查询转换为java。

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

我尝试了很多方法,但我找不到正确的方法。

    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);

但是此对象的结果包含id。所以我只需要摆脱它。

1 个答案:

答案 0 :(得分:4)

您需要将检索到的字段作为findOne方法的第二个参数

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

dbcoll.findOne(query, retrievedField);

此外,如果您想要检索您显示的确切查询,我认为您需要将elemMatch对象附加到retrieveFields,而不是将其添加到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);