我的数据结构如下:
{
"_id" : .....,
"topicId" : topicId1,
"category": .....,
"other things"....,
"posts": [
{postId:id1,
username:.....,
postBody: 'some text here'
},
{postId:id2,
username:.....,
postBody: ' some other text here'
}
]
}
我的目标是找到一个topicId
等于某个ID的文档,然后在posts
中找到一个postId
等于某个ID的对象,最后更新postBody
在该对象中。
最后应该看起来像这样:
{
"_id" : .....,
"topicId" : topicId1,
"category": .....,
"other things"....,
"posts": [
{postId:id1,
username:.....,
postBody: 'some text here'
},
{postId:id2,
username:.....,
postBody: 'HERE IS UPDATED TEXT'
}
]
}
这是我删除帖子的方式:
db.collection('topics').findOneAndUpdate({ 'topicId': topicId }, { $pull: { 'posts': { 'postId': postId } } })
但是我不知道如何根据我的数据结构更新它。我将不胜感激。
答案 0 :(得分:2)
您可以尝试以下方法:
01)文档示例:
{
"topicId" : "5db85e379a17899b8ba631ca",
"category": "category",
"other things": "Other Things",
"posts": [
{
postId: "5dae22702486f7d89ba7633c",
username: "TheUserName",
postBody: 'Some Text Here'
},
{
postId: "5db85e439a17899b8ba631cd",
username: 'TheOtherUserName',
postBody: 'Some Other Text Here'
}
]
}
02)查询:
db.collection('topics').update(
{"topicId" : "5db85e379a17899b8ba631ca"},
{ $set: { "posts.$[outer].postBody" : "HERE IS UPDATED TEXT" } },
{ multi: true, arrayFilters: [{"outer.postId" : "5db85e439a17899b8ba631cd"}]}
);
答案 1 :(得分:1)
考虑您的数据是
.home .fa, .home .fas {
font-family: FontAwesome!important;
}
您可以按过滤器使用简单的updateOne,然后使用$ set
{
"topicId" : "topicId1",
"posts": [
{"postId":"id1",
"postBody": "some text here"
},
{"postId":"id2",
"postBody": "some other text here"
}
]
}