0

I have the following schema in my mongo document:

{
  //more stuff
  arrayExample:[
    {
      //more stuff as well
      field1: "foo"
    },
    {
      //more stuff as well
      field1: "foo"
    },
    {
      //more stuff as well
      field1: "foo"
    },
    //...
  ]
}

What I want to do is add a field id: ObjectId() to each element inside the arrayExample so I could have something like follows:

    {
  //more stuff
  arrayExample:[
    {
      //more stuff as well
      field1: "foo",
      id: 1
    },
    {
      //more stuff as well
      field1: "foo",
      id: 2
    },
    {
      //more stuff as well
      field1: "foo",
      id: 3
    },
    //...
  ]
}

I tried to do this with an aggregation using map but it didn't work the way I did it. Is there a way to do this? thank you very much

0

1 Answer 1

1

Unfortunatunately there is no built-in way in Aggregation to generate an ObjectId (for now).

But, you can make use of the $function Operator and write a custom code to do that.

Note: The use of the $function method will impact performance significantly

Also, the $function operator will work only on MongoDB Version 4.4 and above

The below sample code will work on Mongo Shell. Convert the ObjectId() part to auto ObjectId generator by a custom JS code in the function method.

db.collection.aggregate([
  {
    "$project": {
      "arrayExample": {
        "$map": {
          "input": "$arrayExample",
          "in": {
            "$mergeObjects": [
              "$$this",
              {
                "$function": {
                  "body": "function() { return {'id': ObjectId()}; }",
                  "args": [],
                  "lang": "js",
                },
              },
            ],
          },
        }
      }
    },
  }
])

Mongo Playground Sample Execution

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

5 Comments

I noticed there is a little problem with this.. the ObjectId is the same in all objects. I did this query through Compass
@RafDor, You are right, I didn't think about this earlier. Apologies. I have updated the answer.
Thank you again!
Glad it helped you out. Do keep in mind that this is slower. Will update the answer if I come across a more optimized solution.
Don't worry just used it once to update some big documents. thx again

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.