0

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: []
}

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Instead of $arrayElemAt: ["$field1", { $subtract: [{ $size: "$field1" }, 1] }] you can simply use $arrayElemAt: ["$field1", -1] - or in Mongo 4.4 just $last: "$field1"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.