首页 > 解决方案 > $pull 文档中的多个对象 - MongoDB

问题描述

    "_id" : ObjectId("5e2f7ae123227916c02f1ce6"),
    "items" : [     {
            "_id" : ObjectId("5e2f89d63a983002e4562fb2"),
            "item_id" : "123",
            "upc" : "ean"

        },
                {
            "_id" : ObjectId("5e2f89d63a983002e4562fb2"),
            "item_id" : "456",
            "upc" : "ean",

        },
            {
            "_id" : ObjectId("5e2f89d63a983002e4562fb2"),
            "item_id" : "242",
            "upc" : "ean",

        } ]
}

我想删除项目数组中的多个对象。我正在使用的查询是..

        db.collection.update({}, {$pull: {items: {item_id: {$in: ["123", "456"] }} } } )

我检查了这个答案链接,这和我的一样。但这对我不起作用。

感谢你的帮助。

标签: mongodb

解决方案


您的查询应该没有任何问题,因为您使用了 .update(),它会从过滤器的结果中更新第一个找到的文档:{'items.item_id': {$in: ["123", "456"] }},因此可能刚刚更新了许多匹配该过滤器条件的文档 -您可能错过了观察,请打印该查询的输出。由于您在过滤器中没有提到任何内容{}- 因此,如果您想更新与通过 update 传递的过滤器匹配的所有文档,请使用.updateMany(){multi : true}作为选项传递给 same .update()

例子 :

db.collection.update({}, {$pull: {items: {item_id: {$in: ["123", "456"] }}}}, {multi: true})

(或者)

db.collection.updateMany({}, {$pull: {items: {item_id: {$in: ["123", "456"] }}}})

推荐阅读