1

I have a huge collection (68017 documents) named "inserogato", imported from PostgreSQL. In PostgreSQL the primary key for the table "inserogato" was "id", but MongoDB create a default primary key named "_id" with an ObjectId type. So I want to copy all values in the field "id" to the field "_id".

Some fields of a document

I've tried this but it only update a document:

db.inserogato.find({"_id" : ObjectId("5abe1d264887072726b19b2e")}).forEach(function(doc) {
    var oldId = doc._id;
    doc._id = NumberLong(doc.id);  
    db.inserogato.remove({ _id: oldId });
    db.inserogato.save(doc);
}); 
  • Possible duplicate of [How update the \_id of one MongoDB Document?](https://stackoverflow.com/questions/4012855/how-update-the-id-of-one-mongodb-document) – Neodan Mar 30 '18 at 13:02

1 Answers1

1

Emanuele, you can't remove nor edit the _id of a MongoDB collection. If that's what you need to accomplish you will need to create a new collection with the correct id.

Steps:

  1. Duplicate the collection (Original/Copy)
  2. Delete the original
  3. Recreate the original with the correct _id

If you wanna follow your example you need to iterate over all collection (do not specify an _id)

db.inserogato.find({}).forEach(function(doc) {
 var oldId = doc._id;
 doc._id = NumberLong(doc.id);  
 db.inserogato.remove({ _id: oldId });
 db.inserogato.save(doc);
}); 
Graciano
  • 508
  • 4
  • 11
  • Sorry for late reply! You're idea is the right path to follow, but that code only worked for 8000 or 10000 documents but than it gave me error! Following this idea I found another solution! I simply wrote a Java program that recreate the original collection with the correct _id and it worked! – Emanuele Crema Apr 10 '18 at 14:16