0
{
"Districts" :
[{ "name" : "Krishna"
, "Locations" : [{ "name" : "Vijayawada"}
,{ "name" : "Machilipatnam"}]}
, { "name" : "Guntur"
, "Locations" : [{ "name" : "Satenpalli"}]}
]
, "_id" : 1
, "name" : "Andhra Pradesh"
}
我想創建一個更加位置「Achampet」如果區名稱爲「貢土爾」這樣的結果應該是下面這樣。即使我嘗試多次添加Achampet,結果也應該是一樣的。
{
"Districts" :
[{ "name" : "Krishna"
, "Locations" : [{ "name" : "Vijayawada"}
,{ "name" : "Machilipatnam"}]}
, { "name" : "Guntur"
, "Locations" : [{ "name" : "Satenpalli"}
,{ "name" : "Achampet"}]}
]
, "_id" : 1
, "name" : "Andhra Pradesh"
}
但我的Java代碼不起作用
DBObject newLoc = new BasicDBObject("Districts", new BasicDBObject("name", distName).append("Locations", new BasicDBObject("name", locName)));
if (statesColl.findOne(newLoc) == null) {
DBObject updateLoc = new BasicDBObject("$push", newLoc);
statesColl.update(queryDist, updateLoc);
}
它創建一個新的區每次我嘗試添加位置。我怎樣才能解決這個問題?
感謝。上面的代碼在我的代碼中添加了兩次Achampet。我怎樣才能檢查一個特定的位置是否已經在集合中? – yalkris
從帖子中的問題中可以看出,請編輯。我編輯了我的代碼,使用['$ addToSet'](http://docs.mongodb.org/manual/reference/operator/update/addToSet/)而不是['$ push'](http:// docs。 mongodb.org/manual/reference/operator/update/push/)。如果元素不存在,那隻會添加到數組中。 –
相應地修改了我的問題。謝謝 – yalkris