Lisa
Lisa

Reputation: 2139

Changing _id in MongoDb

just curious - I've got a bunch of records in a MongoDB collection that have _id set to something that was defined outside Mongo (They are the ID's the data had when it was in MySQL, and the were imported with _id being set to the MySQL ID). What would be the best way (preferably with PHP) to convert those ID's to something Mongo generated?

So instead of a record having _id = 500, it would have an _id = 53fcf8d6c4d3f7df129e3245.

Thanks!

Upvotes: 1

Views: 134

Answers (1)

Trudbert
Trudbert

Reputation: 3198

You can not update the _id so the only way will be to retrieve all documents from the database and insert them either with a new _id you generated yourself (documentation here) or without an _id field so (pseudocode because I don't know the php driver):

 for (i=0;i<max_mysql_id;i++){
     doc = db.find({_id:i},{_id :0}); //Select document without the _id field
     db.insert(doc);
     db.remove({_id:i});
 } 

assuming you know the _ids you inserted.

Upvotes: 1

Related Questions