2

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

Nic Cottrell
  • 9,401
  • 7
  • 53
  • 76
Ben McCann
  • 18,548
  • 25
  • 83
  • 101

2 Answers2

5

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.

-2

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

Benjamin
  • 739
  • 4
  • 6
  • I'm fine with creating a new object and deleting the old one, but is it really impossible to change the _id even doing that? I want the _id to be a string and not an ObjectId. Do I need to create a new object and copy all the properties and values to it? – Ben McCann Apr 17 '13 at 23:29
  • 1
    It is impossible to change the _id of an existing object. Once the object is saved, _id cannot be changed. _id can be a string if you'd like, but you'll need to create new objects and delete old ones to accomplish this. – Benjamin Apr 17 '13 at 23:41
  • 2
    @Benjamin you are missing the point - OP is trying to insert a new document with an _id he is setting. There is, in fact, a bug in 2.4.2 shell https://jira.mongodb.org/browse/SERVER-9385 – Asya Kamsky Apr 18 '13 at 04:28