2

I have a document with fields "MyElement" and "MyArray". I want to update my entire collection so that MyElement also appears as the initial item of MyArray.

I tried the following, but it did not work: .updateMany({}, {$push:{MyArray:{$each:["$MyElement"],$position: 0}}})

This just pushed the string literal $MyElement, not the actual value. How do I refer to the actual value?

1 Answer 1

2

You could just use $concatArrays inside of an Updates with Aggregation Pipeline. That will allow the $MyElement variable to be parsed as the actual value and not the string literal. The aggregation pipeline is what allows you to use the variable.

It might look like:

db.collection.updateMany({},
[
  {
    $set: {
      "MyArray": {
        $concatArrays: [
          [
            "$MyElement"
          ],
          "$MyArray"
        ]
      }
    }
  }
]);

See HERE for a working example.

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

Comments

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.