如何从MongoDB集合中移除所有匹配的数组元素?
MongoDB移除数组中指定type的所有元素
你的集合结构示例:
{ "_id" : ObjectId("62e25c91dab0625cc8604198"), "sources" : [ { "createDate" : ISODate("2022-07-25T17:16:12.407+02:00"), "type" : "name1" }, { "createDate" : ISODate("2022-07-25T17:16:12.407+02:00"), "type" : "name2" } ] }
你当前的语句能匹配但无法移除所有目标项,问题出在两点:
- 默认
update()只更新第一个匹配的文档,不会处理所有符合条件的文档 $pull搭配单条件时不需要$elemMatch,可以简化写法
正确写法一:使用update加multi选项
db.collection.update( {}, { $pull: { "sources": { "type": "name2" } } }, { multi: true } )
{}作为查询条件,匹配集合中所有文档$pull直接指定数组字段sources的匹配条件,会移除数组中所有type为name2的元素multi: true确保更新集合中所有符合条件的文档
正确写法二:使用updateMany(MongoDB 4.2+推荐)
db.collection.updateMany( {}, { $pull: { "sources": { "type": "name2" } } } )
updateMany本身就会更新所有匹配的文档,不需要额外加multi参数,写法更直观。
执行后,所有文档的sources数组中type为name2的元素都会被移除。
内容的提问来源于stack exchange,提问作者stacker
相关产品推荐
相关产品推荐

