MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Mongodb aggiorna tutti i documenti con ID univoco

Se stai usando la versione MongoDB>=4.4 puoi provare questo:

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

Uscita

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