2

我需要将以下 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 。所以我只需要摆脱它。

4

1 回答 1

4

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

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

dbcoll.findOne(query, retrievedField);

此外,如果您想检索您显示的确切查询,我认为您需要将 elemMatch 对象附加到检索字段,而不是将其添加到 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);
于 2013-01-25T12:13:47.713 回答