2

I am working on a project using MongoDB and storing users data with their email as _id field.

Now realizing that that is a stupid idea, I wanna add an extra field, let's say "userid" as the new _id field of this collection and let the email as regular field.

Is it possible to do that?

Thank you

Community
  • 1
  • 1
Arief
  • 6,055
  • 7
  • 37
  • 41

1 Answers1

3

It is not possible tp update the _id of a document.

Currently (and probably for the forseeable future) the only way to modify the _id field is to actually remove your old document and reinsert with a new _id:

// Insert our test doc
db.c.insert({_id:1,name:'sammaye'});

// Get it back out
doc=db.c.find({name:'sammaye'});

// Now lets update by removing it first
db.c.remove({_id:doc._id});

// Change the old _id to a new one
doc._id=2;

// Reinsert it and now it has new _id
db.c.insert(doc);
Sammaye
  • 43,242
  • 7
  • 104
  • 146