Home > Enterprise >  mongodb update document from first element of array
mongodb update document from first element of array

Time:12-07

Consider a collection client with the following documents:

[
  {
    "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"
      }
    ]
  }
]

I am attempting to set a field (ownershipClientCode) as the first element of the clientIds array. The result should be like that:

[
  {
    "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"
      }
    ],
    
  }
]

I'm using this query but I can't get sub object from the first element in the array

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

This query add the all object but I want only the field (clientClusterCode).

Some thing like that

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

I'm using mongodb 4.0.0

CodePudding user response:

You're very close: https://mongoplayground.net/p/HY1Pj0P4z12

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

You can use the dot notation within the $arrayElemAt as well as when you defining the field name.

To directly set the field, do something like this (use aggregation in the update): https://mongoplayground.net/p/js-usEJSH_A

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

Note: The second method to update needs to be an array, so that it functions as an pipeline.

  • Related