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

如何在MongoDB中删除数组内满足指定条件的嵌套子数组

从MongoDB嵌套数组中过滤指定元素

问题场景

现有文档结构如下:

{
   "_id":"ObjectId(\"30t00594537da2r7awe083va\")",
   "balances":{
      "intraday":[
         [
            1630939075734,
            1899.09
         ],
         [
            1630939435939,
            1899.32
         ],
         [
            1632306730756,
            0
         ],
         [
            1632306759376,
            0
         ],
         [
            1632272012916,
            1372.22
         ]
      ]
   }
}

需要删除balances.intraday数组中所有第二个元素等于0的嵌套子数组,最终期望得到的结果如下:

{
   "_id":"ObjectId(\"30t00594537da2r7awe083va\")",
   "balances":{
      "intraday":[
         [
            1630939075734,
            1899.09
         ],
         [
            1630939435939,
            1899.32
         ],
         [
            1632272012916,
            1372.22
         ]
      ]
   }
}

此前尝试使用$pull命令操作,但仅删除了对应索引位置的元素,无法删除整个符合条件的子数组。

可行解决方案

该方案由Tom Slabbaert提供,通过聚合管道配合$filter操作符实现需求,代码如下:

db._get_collection().update_many(
{},
[
  {
    "$set": {
      "balances.intraday": {
        "$filter": {
          "input": "$balances.intraday",
          "cond": {
            "$ne": [
              {
                "$arrayElemAt": [
                  "$$this",
                  1
                ]
              },
              0
            ]
          }
        }
      }
    }
  }
])

方案逻辑说明

  • 采用更新聚合管道的写法,通过$set覆盖原有balances.intraday字段
  • 使用$filter遍历intraday数组的每一个子数组元素
  • 用$arrayElemAt取每个子数组索引为1的元素(也就是第二个元素),保留所有该值不等于0的子数组

内容的提问来源于stack exchange,提问作者yair_elmaliah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:06:05