使用MongoDB从以下代码中的文档中的数组中删除对象


  • 下面给出的是我的文档,我需要从文档中删除对象的注释数组,这样我就可以从前端传递文档id,带有postId
  • 我很累,请帮帮我
{
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
}

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

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

如果要从集合中的每个元素中删除注释对象,只需从update中删除第一个参数即可。类似这样的东西:

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

最新更新