如何更新 mongodb 文档中的 _id 字段 [英] How to update the _id field in a mongodb document

查看:63
本文介绍了如何更新 mongodb 文档中的 _id 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的文件:

{
  _id: "1232014",
  account: "123",
  year: 2014,
  country: 826
}

_id 字段由 account 字段和 year 字段组合而成.

The _id field is made up of the account field and the year field combined.

然而,我后来发现同一年的同一个账户可以有不同国家的数据,而且我收到了重复键错误.

However, I've since found that the same account in the same year can have data in different countries, and I'm getting a duplicate key error.

我需要做的是将 country 字段也作为 _id 字段的一部分,例如

What I need to do is have the country field as part of the _id field too e.g.

_id: "1232014826"

由于我使用文档中的值作为更新的一部分,我认为我不能使用 $set,所以我尝试使用 save()forEach() 查询中:

Since I'm using a value from within the document as part of the update, I don't think I can use $set, so I've tried to use save() within a forEach() query instead:

db.account_data.find({"_id" : "1232014"}).forEach(function(doc) {
    doc._id = doc._id + doc.country;
    db.collection.save(doc);
});

这不起作用.

有没有办法更新_id?或者这是不可能的,因为它是主键字段?

Is there any way to update _id? Or is this impossible because it is primary key field?

推荐答案

是的,这是不可能的,因为它一个主键字段.如果您真的想这样做,那么您实际上正在做的是插入一个新文档并删除旧文档:

Yes it is impossible because it is a primary key field. If you actually want to do this then what you are actually doing is inserting a new document and removing the old one:

db.account_data.find({"_id" : "1232014"}).forEach(function(doc) {
    var oldId = doc._id;
    var doc._id = doc._id + doc.country;
    db.collection.remove({ _id: oldId });
    db.collection.save(doc);
});

这篇关于如何更新 mongodb 文档中的 _id 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆