如何使用 java 驱动程序在 mongodb 中的嵌入式文档中推送评论
how to push a comment in an embedded document in mongodb with java driver
我有以下文件:
</p>
<pre><code>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"
} 在 post ID 下的评论部分:1 来自 java
你需要匹配 postId 1,然后将新评论推送到 "comments",像这样:
db.[your collection name].update({"RoomPost" :{$elemMatch :{"postId" : 1}}}, {$push : {"RoomPost.$.comments": {"comment3" :"some comment"}}})
用 java 驱动程序编写它很容易,'update' 部分是这样的:
BasicDBObject update = new BasicDBObject("$push", new BasicDBObject("RoomPost.$.comments",new BasicDBObject("comment3" ,"some comment" ) ))
希望对您有所帮助。
我有以下文件:
</p>
<pre><code>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" } 在 post ID 下的评论部分:1 来自 java
你需要匹配 postId 1,然后将新评论推送到 "comments",像这样:
db.[your collection name].update({"RoomPost" :{$elemMatch :{"postId" : 1}}}, {$push : {"RoomPost.$.comments": {"comment3" :"some comment"}}})
用 java 驱动程序编写它很容易,'update' 部分是这样的:
BasicDBObject update = new BasicDBObject("$push", new BasicDBObject("RoomPost.$.comments",new BasicDBObject("comment3" ,"some comment" ) ))
希望对您有所帮助。