Ben McCann
Ben McCann

Reputation: 19004

Reassign MongoDB _id in shell

I'm trying to use the MongoDB to reassign IDs. However, it is not setting IDs equal to the value I assign, but rather it is creating a new ObjectId. How do I assign my own ID?

> db.pGitHub.find();
{ "_id" : ObjectId("516f202da1faf201daa15635"), 
     "url" : { "raw" : "https://github.com/Quatlus", 
     "domain" : "github.com", "canonical" : "https://github.com/quatlus" } }
{ "_id" : ObjectId("516f202da1faf201daa15636"), 
      "url" : { "raw" : "https://github.com/Quasii", 
      "domain" : "github.com", "canonical" : "https://github.com/quasii" } }

> db.pGitHub.find().forEach(function(myProfile) {   
       var oldId = myProfile._id;   
       myProfile._id = 'exampleid';   
       db.pGitHub.save(myProfile);   
       db.pGitHub.remove({_id: oldId}); 
  });

> db.pGitHub.find();
{ "_id" : ObjectId("516f204da1faf201daa15637"), 
      "url" : { "raw" : "https://github.com/Quatlus", 
      "domain" : "github.com", "canonical" : "https://github.com/quatlus" } }
{ "_id" : ObjectId("516f204da1faf201daa15638"),  
      "url" : { "raw" : "https://github.com/Quasii", 
      "domain" : "github.com", "canonical" : "https://github.com/quasii" } }

I'm using Mongo 2.4.2

Upvotes: 2

Views: 283

Answers (2)

user2292972
user2292972

Reputation: 66

Ben, your statements are correct. It's just mongo shell 2.4.2 behaves somehow different than others (server is not affected). You can use mongo shell binary from 2.4.1 for your purpose.

Upvotes: 5

Benjamin
Benjamin

Reputation: 749

You can only set object IDs before they've been created. After the fact, they cannot be changed. What you're probably doing is creating new objects when you change the IDs like that.

There's more information in the MongoDB docs

Upvotes: -2

Related Questions