在 MongoDB 对象的数组内添加一个字段,其值根据同一嵌套数组内的其他值动态计算

问题描述 投票:0回答:1

我有一个简单的 MongoDB 对象数组,具有以下结构:

[
  {
    "_id": {
      "$oid": "6688c2f6b79f2bfefb751d5f"
    },
    "date": "06/07/2024",
    "serviceStatus": [
      {
        "home": "http://www.bbc.co.uk/ontologies/passport/home/Marathi",
        "count": 8
      },
      {
        "home": "http://www.bbc.co.uk/ontologies/passport/home/Indonesia",
        "count": 4
      },
   ]
  },
  {
    "_id": {
      "$oid": "66860a80b79f2bfefb7513cc"
    },
    "date": "04/07/2024",
    "serviceStatus": [
      {
        "home": "http://www.bbc.co.uk/ontologies/passport/home/Pashto",
        "count": 10
      },
      {
        "home": "http://www.bbc.co.uk/ontologies/passport/home/Zhongwen",
        "count": 4
      }
    ]
  }
]

我尝试使用此聚合管道命令在 serviceStatus 数组中添加一个新字段,以获取每个对象中 serviceStatus.home 值的缩写版本:

{
    $addFields: {
      "serviceStatus.homeShort": { $substrCP: [ "$serviceStatus.home", 0, 2 ] },
    }

但是这会返回错误:

PlanExecutor error during aggregation :: caused by :: can't convert from BSON type array to String 
如果该命令用于分配静态值,则可以正常工作,但不能动态工作。

是否可以使用聚合管道在 MongoDB 集合中的嵌套数组中添加字段,并根据同一数组中已存在的值填充该字段?或者这是否需要将数组展开到单独的对象中,将字段添加到每个对象中,然后重新分组?

mongodb mongodb-query aggregation
1个回答
0
投票

由于您正在处理数组字段,因此您需要使用

$map
迭代条目,并使用
$mergeObjects
将新字段附加到对象。
$merge
用于更新回集合中,如果不需要,可以跳过它。

db.collection.aggregate([
  {
    "$set": {
      "serviceStatus": {
        "$map": {
          "input": "$serviceStatus",
          "as": "ss",
          "in": {
            "$mergeObjects": [
              "$$ss",
              {
                "homeShort": {
                  "$substrCP": [
                    "$$ss.home",
                    0,
                    2
                  ]
                }
              }
            ]
          }
        }
      }
    }
  },
  {
    "$merge": {
      "into": "collection"
    }
  }
])

蒙戈游乐场

© www.soinside.com 2019 - 2024. All rights reserved.