1
votes

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);
}); 
1

1 Answers

0
votes

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);
});