You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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"
        }
    ]
}

你当前的语句能匹配但无法移除所有目标项,问题出在两点:

  1. 默认update()只更新第一个匹配的文档,不会处理所有符合条件的文档
  2. $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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 22:47:37