如何在Mongoose中从数组中删除嵌套对象

10
这是我的第一个网络应用程序,我需要删除一个嵌套的数组项。如何使用此模式在Mongoose中删除对象:
User: {
    event: [{_id:12345, title: "this"},{_id:12346, title:"that"}]
}

我该如何在mongoose/Mongo中删除id:12346

3个回答

17

使用$pull从类似以下的项目数组中删除项目:

db.User.update(
  { },
  { $pull: { event: { _id: 12346 } } }
)

$pull运算符会从现有数组中移除与指定条件匹配的一个或多个值。

第一个参数中的空对象是用来查找文档的query。以上方法将在集合中的所有文档中,删除event数组中具有_id: 12345的项目。 如果数组中有多个项目符合条件,可以将multi选项设置为true,如下所示:

db.User.update(
  { },
  { $pull: { event: { _id: 12346 } } },
  { multi: true}
)

如果我没看错的话,这会在所有内容中搜索 event { _id: 123456) 并将其删除,对吗?如果需要,我可以通过在第一个条件中放置一个ID来仅删除一个实例,对吗? - illcrx
它将从集合“User”的所有文档中的数组“event”中删除所有具有“_id:123456”的“items”。如果您想要删除所有匹配的文档,只需使用“remove”方法即可。 - Supradeep
$pull will delete specific value/values in an existing array and not the whole document that matches the condition. If you want to delete the whole document that matches the condition, use db.collection.remove - Supradeep
2
4年后,这仍然是正确的答案。谢谢@Supradeep! - John Nyingi
@Supradeep如果我想要根据它们的ID删除多个嵌套对象呢?? - m-naeem66622

2
User.findOneAndUpdate({ _id: "12346" }, { $pull: { event: { _id: "12346" } } }, { new: true });

为什么这不是一个好的解决方案? - Alexandre Mahdhaoui

1

Findone将搜索id,如果未找到则返回错误,否则remove将起作用。

   User.findOne({id:12346}, function (err, User) {
        if (err) {
            return;
        }
        User.remove(function (err) {
            // if no error, your model is removed
        });
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接