mongodb从数组的第一个元素更新文档

knsnq2tg  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(148)

假设有一个具有以下文档的收集客户端:

[
  {
    "id": 1,
    "Name": "Susie",
    "ownership" : {
        "ownershipContextCode" : "C1"
    },
    "clientIds": [
      {
        "clientClusterCode": "clientClusterCode_1",
        "clientId": "11"
      }
    ]
  },
  {
    "id": 2,
    "Name": "John",
    "ownership" : {
        "ownershipContextCode" : "C2"
    },
    "clientIds": [
      {
        "clientClusterCode": "clientClusterCode_2",
        "clientId": "22"
      }
    ]
  }
]

我尝试将字段(ownershipClientCode)设置为clientIds数组的第一个元素。结果应该如下所示:

[
  {
    "id": 1,
    "Name": "Susie",
    "ownership" : {
        "ownershipContextCode" : "C1",
        "ownershipClientCode" : "clientClusterCode_1"
    },
    "clientIds": [
      {
        "clientClusterCode": "clientClusterCode_1",
        "clientId": "11"
      }
    ],
    
  },
  {
    "id": 2,
    "Name": "John",
    "ownership" : {
        "ownershipContextCode" : "C2",
        "ownershipClientCode" : "clientClusterCode_2"
    },
    "clientIds": [
      {
        "clientClusterCode": "clientClusterCode_2",
        "clientId": "22"
      }
    ],
    
  }
]

我正在使用此查询,但无法从数组中的第一个元素获取子对象

db.collection.aggregate([
  {
    $addFields: {
      "Last Semester": {
        "$arrayElemAt": [
          "$clientIds",
          0
        ]
      }
    }
  }
])

此查询添加all对象,但我只需要字段(clientClusterCode)。
诸如此类的事情

db.collection.aggregate([
  {
    $addFields: {
      "Last Semester": {
        "$arrayElemAt": [
          "$clientIds",
          0
        ].clientClusterCode
      }
    }
  }
])

我使用的是mongodb 4.0.0

nxowjjhe

nxowjjhe1#

你很接近了:https://mongoplayground.net/p/HY1Pj0P4z12

db.collection.aggregate([
  {
    $addFields: {
      "ownership.ownershipClientCode": {
        "$arrayElemAt": [
          "$clientIds.clientClusterCode",
          0
        ]
      }
    }
  }
])

您可以在$arrayElemAt中使用点标记法,也可以在定义字段名称时使用点标记法。
要直接设置字段,请执行类似以下操作(在更新中使用聚合):https://mongoplayground.net/p/js-usEJSH_A

db.collection.update({},
[
  {
    $set: {
      "ownership.ownershipClientCode": {
        "$arrayElemAt": [
          "$clientIds.clientClusterCode",
          0
        ]
      }
    }
  }
],
{
  multi: true
})

注意:update的第二个方法需要是数组,这样它才能起到管道的作用。

相关问题