在shell中重新分配MongoDB _id

Ben*_*ann 2 mongodb mongodb-shell

我正在尝试使用MongoDB来重新分配ID.但是,它不是将ID设置为等于我分配的值,而是创建一个新的ObjectId.我如何分配自己的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" } }
Run Code Online (Sandbox Code Playgroud)

我正在使用Mongo 2.4.2

小智 5

本,你的陈述是正确的.它只是mongo shell 2.4.2的行为与其他行为不同(服务器不受影响).您可以使用2.4.1中的mongo shell二进制文件.