как добавить комментарий во встроенный документ в mongodb с помощью java-драйвера

I have the below document:

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"
            }
        ]
    }
]

}

Как добавить новый комментарий {"comment3":"push comment from java", "author":"Java"} в разделе комментариев под идентификатором сообщения: 1 из java


person Ashish Kastury    schedule 17.02.2016    source источник


Ответы (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" ) ))

Надеюсь, поможет.

person Yair Harel    schedule 17.02.2016