首页 文章

如何更新一个MongoDB文档的_id?

提问于
浏览
105

我想要更新一个文档的_id MongoDB . 我知道这不是一个非常好的实践 . 但由于某些技术原因,我需要更新它 . 但如果我尝试更新它,我有:

> db.clients.update({'_id':ObjectId("4cc45467c55f4d2d2a000002")}, {'$set':{'_id':ObjectId("4c8a331bda76c559ef000004")}});
Mod on _id not allowed

而且没有更新 . 我怎么能真正更新它?

4 回答

  • 25

    要为整个集合执行此操作,您还可以使用循环(基于Niels示例):

    db.status.find().forEach(function(doc){ 
        doc._id=doc.UserId; db.status_new.insert(doc);
    });
    db.status_new.renameCollection("status", true);
    

    在这种情况下,UserId是我想要使用的新ID

  • 177

    在这里,我有一个解决方案,可以避免多个请求,循环和旧文档删除 .

    您可以使用以下内容手动创建新想法: _id:ObjectId() 但是如果知道Mongo将自动分配_id(如果缺少),则可以使用聚合创建包含文档所有字段的 $project ,但省略字段_id . 然后你可以用 $out 保存它

    所以如果你的文件是:

    {
    "_id":ObjectId("5b5ed345cfbce6787588e480"),
    "title": "foo",
    "description": "bar"
    }
    

    然后你的查询将是:

    db.getCollection('myCollection').aggregate([
            {$match:
                 {_id: ObjectId("5b5ed345cfbce6787588e480")}
            }        
            {$project:
                {
                 title: '$title',
                 description: '$description'             
                }     
            },
            {$out: 'myCollection'}
        ])
    
  • 0

    如果你想在同一个集合中重命名_id(例如,如果你想为一些_ids添加前缀):

    db.someCollection.find().snapshot().forEach(function(doc) { 
       if (doc._id.indexOf("2019:") != 0) {
           print("Processing: " + doc._id);
           var oldDocId = doc._id;
           doc._id = "2019:" + doc._id; 
           db.someCollection.insert(doc);
           db.someCollection.remove({_id: oldDocId});
       }
    });
    

    if(doc._id.indexOf("2019:")!= 0){...需要防止无限循环,因为forEach选择插入的文档,甚至使用.snapshot()方法 .

  • 1

    你无法更新它 . 您必须使用新的 _id 保存文档,然后删除旧文档 .

    // store the document in a variable
    doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})
    
    // set a new _id on the document
    doc._id = ObjectId("4c8a331bda76c559ef000004")
    
    // insert the document, using the new _id
    db.clients.insert(doc)
    
    // remove the document with the old _id
    db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})
    

相关问题