首页 > 解决方案 > 使用 MongoDB 从以下代码中的文档中的数组中删除对象?

问题描述

{
  likes: [],
  _id: 5ea4375f49e4355094073330,
  title: 'abc',
  body: 'abc',
  photo: 'no pic',
  postedBy: 5e9aa457de91831e5c9f5005,
  comments: [
    {
      _id: 5ea437c2a584ce5ac0147da1,
      text: 'sadsadsad',
      postedBy: [Object]
    },
    {
      _id: 5ea437c5a584ce5ac0147da2,
      text: 'sadsadsad',
      postedBy: [Object]
    },
    {
      _id: 5ea437c7a584ce5ac0147da3,
      text: 'sadsadsad',
      postedBy: [Object]
    }
  ],
  __v: 0
}

标签: node.jsmongodbexpress

解决方案


如果要从数组中删除特定元素,comments可以使用以下查询:

db.mycollection. updateOne(
       {'_id': ObjectId("5ea4375f49e4355094073330")},
       { $pull: { "comments" : { _id: ObjectId("5ea437c2a584ce5ac0147da1") } } }
);

如果要从集合中的每个元素中删除注释对象,只需从update. 像这样的东西:

db.mycollection.updateMany(
       { },
       { $pull: { "comments" : { _id: ObjectId("5ea437c2a584ce5ac0147da1") } } }
);

推荐阅读