MongoDB / Java:在子文档中插入文档

时间:2014-03-13 15:01:09

标签: java mongodb

我正在尝试将文档添加到子文档中,但不会添加。

这是代码:

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没有添加,我无法弄清楚原因:(

更新:这是我擅长的代码

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

1 个答案:

答案 0 :(得分: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);

因为您正在更新" document1"在用于更新"文件"之后。然后第二次更新不会更新"文件"同样。