2014-03-13 127 views
2

我正在嘗試將文檔添加到子文檔中,但未添加。MongoDB/Java:在子文檔中插入文檔

這是代碼:

MongoClient mongo = new MongoClient("localhost", 27017); 
DB db = mongo.getDB("testdb"); 

DBCollection test = db.getCollection("test"); 
BasicDBObject document = new BasicDBObject(); 
document.put("username", "user"); 
test.insert(document); 

BasicDBObject document1 = new BasicDBObject(); 
document1.put("title", "test1"); 
BasicDBObject updateCommand = new BasicDBObject(); 
updateCommand.put("$addToSet", new BasicDBObject("test", document1)); 
test.update(document, updateCommand); 

BasicDBObject document2 = new BasicDBObject(); 
document2.put("title", "test2"); 
BasicDBObject updateCommand1 = new BasicDBObject(); 
updateCommand1.put("$addToSet", new BasicDBObject("test", document2)); 
test.update(document1, updateCommand1); 

結果是:

{ 
    "_id" : ObjectId("5321c6b0c2e682dc2fb97774"), 
    "test" : [ 
     { 
      "title" : "test1" 
     } 
    ], 
    "username" : "user" 
} 

正如你可以看到不加test2的,我想不通爲什麼:(

UPDATE :這是我擅長的代碼

"_id" : ObjectId("5321caa63b81968cb5f23d8c"), 
     "test" : [ 
       { 
         "title" : "test1" 
         "test" : [ 
            { 
              "test" : "test2" 
            }] 
       }, 
       { 
         "title" : "test2" 
       } 
     ], 
     "username" : "user1" 
+0

我認爲問題在於你的查詢文檔在最後一行是錯誤的。它應該是類似於 'test.update(document,updateCommand1);' – evanchooly

+0

我希望test2在IN test1不在其旁邊 –

回答

0

我猜你需要扭轉操作:

BasicDBObject document1 = new BasicDBObject(); 
document1.put("title", "test1"); 

BasicDBObject document2 = new BasicDBObject(); 
document2.put("title", "test2"); 
BasicDBObject updateCommand1 = new BasicDBObject(); 
updateCommand1.put("$addToSet", new BasicDBObject("test", document2)); 
test.update(document1, updateCommand1); 

BasicDBObject updateCommand = new BasicDBObject(); 
updateCommand.put("$addToSet", new BasicDBObject("test", document1)); 
test.update(document, updateCommand); 

因爲你在更新後,被用來更新「文件」中的「文檔1」。然後第二個更新也不會更新「文檔」。