2014-03-26 31 views
0

MongoDB的查詢中數組的數組,並添加如果不存在

{ 
"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); 
      } 

它創建一個新的區每次我嘗試添加位置。我怎樣才能解決這個問題?

回答

0

這是如何使用的$ positional操作者在Java中做到這一點:

... 
DBObject selectQuery = new BasicDBObject("_id", 1); // Matches the document 
selectQuery.append("Districts.name", distName); // Matches the element in the array where District name = Guntur 

BasicDBObject updateFields = new BasicDBObject(); 
updateFields.put("Districts.$.Locations", new BasicDBObject("name":"Achampet")); 

DBObject updateQuery = new BasicDBObject("$addToSet", updateFields); 
statesColl.update(selectQuery, updateQuery); 
... 
+0

感謝。上面的代碼在我的代碼中添加了兩次Achampet。我怎樣才能檢查一個特定的位置是否已經在集合中? – yalkris

+1

從帖子中的問題中可以看出,請編輯。我編輯了我的代碼,使用['$ addToSet'](http://docs.mongodb.org/manual/reference/operator/update/addToSet/)而不是['$ push'](http:// docs。 mongodb.org/manual/reference/operator/update/push/)。如果元素不存在,那隻會添加到數組中。 –

+0

相應地修改了我的問題。謝謝 – yalkris

相關問題