Gibbs
Gibbs

Reputation: 22956

How to generate unique field for all documents

I want to do something as below:

db.coll.updateMany(
  {}, 
  {
    $push:{
      "newField":new ObjectId()
    }
  }
)

I want newField to have unique ids for all docs. But that's not the case as ObjectIds are generated on driver side.

How can I do this? MongoDB version is 4.2

Upvotes: 3

Views: 102

Answers (3)

D. SM
D. SM

Reputation: 14480

Use $exists:false in the query on the field you are adding, execute in a loop until you have zero documents updated.

MongoDB Enterprise ruby-driver-rs:PRIMARY> db.foo.insert({a:1})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise ruby-driver-rs:PRIMARY> db.foo.update({new:{$exists:false}},{$set:{new:new ObjectId()}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
MongoDB Enterprise ruby-driver-rs:PRIMARY> db.foo.find()
{ "_id" : ObjectId("5f1b5bcc74541096256ab898"), "a" : 1, "new" : ObjectId("5f1b5bd574541096256ab899") }

Upvotes: 1

turivishal
turivishal

Reputation: 36104

For the temporary solution you can try,

db.coll.find().forEach(function(doc){
    doc.newField = doc.newField ? doc.newField : [];
    doc.newField.push(new ObjectId());
    db.coll.save(doc);
})

Upvotes: 0

ROHIT W
ROHIT W

Reputation: 36

You can try this :

db.coll.ensureIndex( { newField: 1 }, { unique:true, sparse:true } );

Upvotes: 0

Related Questions