MongoDB-如何更新数组中的对象?

时间:2019-10-29 17:09:02

标签: mongodb

我的数据结构如下:

{
  "_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 } } })

但是我不知道如何根据我的数据结构更新它。我将不胜感激。

2 个答案:

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