moman822
moman822

Reputation: 1954

MongoDB - add last element of array to existing array in other field

How can I take the last element in an array and add it to an array in another field, in the same document? As below, I want to add "z" to field2.

{
   field1: ["x","y","z"],
   field2: []
}

Upvotes: 0

Views: 72

Answers (1)

namar sood
namar sood

Reputation: 1590

You can use Updates with Aggregation Pipeline, which is available in MongoDB versions starting from MongoDB 4.2

Update Query will look something like this

db.collection.update({},[
  {
    $set: {
      field2: {
        $concatArrays: [
          "$field2",
          [
            {
              $arrayElemAt: [
                "$field1",
                {
                  $subtract: [
                    {
                      $size: "$field1"
                    },
                    1
                  ]
                }
              ]
            }
          ]
        ]
      }
    }
  }
])

The above query will take the last element from the field1 array and add it to the field2 array.

PS: If you just want to see the working of aggregation pipeline used in the update, you see it here

Upvotes: 3

Related Questions