Search code examples
node.jsmongodbmongodb-querynode-mongodb-native

Mongodb update all the documents with unique id


I have collection with name products with almost 100k documents. I want to introduce a new key called secondaryKey with unique value uuid in all the documents. I do this using nodejs.

Problem I am facing:-

When I try the below query,

db.collection('products').updateMany({},{"$set":{secondaryKey: uuid()}});

Here it updates all the documents with same uuid value,

I try with loop to update document one by one,but here issues is I don't have filter value in updateOne because I want to update all the documents.

Can anyone please help me here. Thanks :)


Solution

  • If you are using MongoDB version >= 4.4 You can try this:

    db.products.updateMany(
        {},
        [
            {
                $set: {
                    secondaryKey: {
                        $function: {
                            body: function() {
                                return UUID().toString().split('"')[1];
                            },
                            args: [],
                            lang: "js"
                        }
                    }
                }
            }
        ]
    );
    

    Output

    [
      {
        "_id": ObjectId("..."),
        "secondaryKey": "f41b15b7-a0c5-43ed-9d15-69dbafc0ed29"
      },
      {
        "_id": ObjectId("..."),
        "secondaryKey": "50ae7248-a92e-4b10-be7d-126b8083ff64"
      },
      {
        "_id": ObjectId("..."),
        "secondaryKey": "fa778a1a-371b-422a-b73f-8bcff865ad8e"
      }
    ]