【问题标题】:How to alter _id field of MongoDB? [duplicate]如何更改 MongoDB 的 _id 字段? [复制]
【发布时间】:2013-09-22 23:51:10
【问题描述】:

我正在使用 MongoDB 进行一个项目,并将用户数据与他们的电子邮件一起存储为 _id 字段。

现在意识到这是一个愚蠢的想法,我想添加一个额外的字段,让我们说“userid”作为此集合的新 _id 字段,并将电子邮件作为常规字段。

有可能吗?

谢谢

【问题讨论】:

    标签: mongodb nosql


    【解决方案1】:

    不可能更新文档的_id

    目前(并且可能在可预见的将来)修改_id 字段的唯一方法是实际删除旧文档并重新插入新的_id

    // Insert our test doc
    db.c.insert({_id:1,name:'sammaye'});
    
    // Get it back out
    doc=db.c.find({name:'sammaye'});
    
    // Now lets update by removing it first
    db.c.remove({_id:doc._id});
    
    // Change the old _id to a new one
    doc._id=2;
    
    // Reinsert it and now it has new _id
    db.c.insert(doc);
    

    【讨论】:

      猜你喜欢
      • 2014-06-01
      • 2013-11-27
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多