Search code examples
mongodbmongodb-shellnosql

Generate a new row, with a new GUID, from the MongoDB shell


I have some documents in a MongoDB collection with a GUID-type key, and I would like to be able to copy them to a new row, with a new GUID, using the shell. I tried this:

db.schedules.find().forEach(function(x) { 
    x._id = null; 
    db.schedules.save(x); 
});

I expected the _id field to auto-generate after I set it to null, but of course that was naive. How, if at all, could I go about generating a new GUID in the shell?

UPDATE

Apparently not possible to generate a GUID from the shell. I ended up writing a mini-script in C# so as to use the Mongo C# driver.


Solution

  • Try this instead:

    x._id = new ObjectId();
    db.schedules.insert(x);
    

    You can also do:

    delete x._id;
    db.schedules.insert(x);