Home > Software engineering >  Add a unique MongoDb ObjectId to each Object in an existing Array
Add a unique MongoDb ObjectId to each Object in an existing Array

Time:05-01

I have an existing document and I wish to add a unique Object Id to each of the transaction Array Objects.

{
_id: ObjectId(6086d7e7e39add6a5220d0a5),
firstName: "John"
lastName: "Doe"
transactions: [
  {
    date: 2022-04-12T09:00:00.000 00:00
    amount: 286.56
    type: "deposit"
    method: "Bank transfer"
  },
  {
    date: 2022-04-15T09:00:00.000 00:00
    amount: 120.23
    type: "withdrawal"
    method: "cash"
  }]
}

The outcome would be each transactions Object would have a unique ObjectId. I have tried the following query but it add the same ObjectId to all objects:

collection.updateMany({}, [
  {
    $set: {
      transactions: {
        $map: {
          input: "$transactions",
          in: {
            $mergeObjects: ["$$this", { _id: new mongo.ObjectId() }],
          },
        },
      },
    },
  },
]);

Can anyone see why I am getting the same ObjectId written to all of the Objects in the transactions array instead of unique Ids?

CodePudding user response:

The code new mongo.ObjectId() will run on the driver => 1 id for all.
You need the js to run on the server, one time for each member.

Try to replace the new mongo.ObjectId() with the bellow $function code that will run on the server.
In general we should avoid javascript, but i don't think we have an aggregate operator that generates ObjectId's.

Another alternative is to write all the $map function in javascript, again with the use of $function.

*$function requires MongoDB >=4.4

{
  "$function": {
    "body": "function () {return new ObjectId();}",
    "args": [],
    "lang": "js"
  }
}

CodePudding user response:

the _id field in a document cannot be modified.in fact you are tying to modify main objectid. try another name for your transaction_id field.

  • Related