1

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.

Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260

1 Answers1

6

Try this instead:

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

You can also do:

delete x._id;
db.schedules.insert(x);
Eve Freeman
  • 32,467
  • 4
  • 86
  • 101
  • Well, that works, but of course the ID is an ObjectId **ObjectId("4f963746ee633c3aa4a71a60")** rather than the C# GUID **BinData(3,"+Wgv1RJhr0K5/qbi3McvlQ==")**. I suppose that is a feature of the C# driver, and I'll have to use that for this task. – McGarnagle Apr 24 '12 at 05:18
  • Yeah, the shell doesn't have a way to generate GUIDs. If you have a GUID value you can set it in the shell via the BinData wrapper as you show (with base 64), but it can't generate new ones for you. (sorry, missed that you wanted a GUID) – Eve Freeman Apr 24 '12 at 05:38
  • I suspect that you could write a Javascript function to create your GUID and register the function in the MongoDB shell. – Mick Sear Apr 24 '12 at 06:53
  • 1
    Yeah, you probably could. But it might be difficult to make the GUID generator work the same way as the C# GUID generator. – Eve Freeman Apr 24 '12 at 17:22