2013-01-25 92 views
2

我需要將以下mongo查詢轉換爲java。將MongoDB查詢轉換爲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

你需要給檢索領域findOne方法

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

dbcoll.findOne(query, retrievedField); 

同樣的第二個參數,如果你想找回你出我認爲你需要追加elemMatch對象retrievedFields,而不是將它添加到的精確查詢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);