0

我有以下文件:

enter code here

{ "_id" : ObjectId("56c49b52a5b24ba2a979a964"),

"FirstName" : "satvik",
"LastName" : "ponakala",
"Major" : "Information Assurance",
"RoomPost" : [
    {
        "postId" : 1,
        "title" : "I have a room to share at Garden Square",
        "comments" : [
            {
                "comment1" : " i want to join",
                "author" : "ashish"
            },
            {
                "comment2" : " already booked",
                "author" : "puneeth"
            }
        ]
    },
    {
        "postId" : 2,
        "title" : "I have a room to share at Ansley Falls",
        "comments" : [
            {
                "comment1" : " How many can stay",
                "author" : "sandeep"
            },
            {
                "comment2" : "can i come there next sunday??",
                "author" : "sandeep"
            }
        ]
    }
]

}

如何在帖子 ID 下的评论部分添加新评论 { "comment3":"push comment from java", "author":"Java" }:1 from java

4

1 回答 1

1

您需要匹配 postId 1,然后将新评论推送到“评论”,如下所示:

db.[your collection name].update({"RoomPost" :{$elemMatch :{"postId" : 1}}}, {$push : {"RoomPost.$.comments": {"comment3" :"some comment"}}})

使用 java 驱动程序编写它很容易,“更新”部分是这样的:

BasicDBObject  update = new BasicDBObject("$push", new BasicDBObject("RoomPost.$.comments",new BasicDBObject("comment3" ,"some comment" ) ))

希望能帮助到你。

于 2016-02-17T21:51:22.070 回答