-1

New in mongodb, my requirement is to update the _id field for entire collection as follows:

orignal : _id: ObjectId("4cc45467c55f4d2d2a000002")

required: _id: 4cc45467c55f4d2d2a000002

I want to truncate 'ObjectId("' from beginning and '")' from end of all documents from whole collection.

Moreover I have seen following on a similar post but its all manual I have millions of rows/document wish to have a function or some thing to do it of all document.

// store the document in a variable
doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})
// set a new _id on the document
doc._id = ObjectId("4c8a331bda76c559ef000004")
// insert the document, using the new _id
db.clients.insert(doc)
// remove the document with the old _id
db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})

Thanks

kranteg
  • 931
  • 1
  • 7
  • 15
user3706888
  • 159
  • 2
  • 11
  • Why are you required to do this? MongoDB uses the ObjectID object in order to identify records. – Josh Beam Jun 04 '14 at 12:29
  • I dont think you can manipulate the default id of a document. As it states, it is an Object id which mongodb creates to uniquely identity each document inside a collection. However, you can create your own id in case you want to customize it. And you can generate that id somewhat similar to what mongo generates by default using various combinations of host, server, time, date, etc. OR if you want the same content, you can go by your method. Fetch object id, then Object_id.valueOf() and then update that document – AppleBud Jun 04 '14 at 12:32
  • 1
    Your question doesn't really make sense. The `ObjectId("` and `")` parts that you're looking to remove aren't actually in your docs; they're just shown as type information in the shell when you query it. – JohnnyHK Jun 04 '14 at 12:40
  • possible duplicate of [How update the \_id of one MongoDB Document?](http://stackoverflow.com/questions/4012855/how-update-the-id-of-one-mongodb-document) – Simulant Jun 04 '14 at 13:44

1 Answers1

0

MongodDB does not allow a modification of the _id field at all. So once you created a document you cannot change the _ids value.

The error message if you try to update the _id is: Mod on _id not allowed

If you want to do a change to the value of _id (as you already found) you have to copy your document to a variable, change the _id, insert the new document and delete the old one. There is no other way.

Simulant
  • 19,190
  • 8
  • 63
  • 98