如何为MongoDB中的所有文档重命名字段? [英] How can I rename a field for all documents in MongoDB?

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

问题描述

假设我在MongoDB中有一个具有5000条记录的集合,每条记录都类似于:

Assuming I have a collection in MongoDB with 5000 records, each containing something similar to:

{
"occupation":"Doctor",
"name": {
   "first":"Jimmy",
   "additional":"Smith"
}

在所有文档中,是否有简便的方法将字段其他"重命名为最后"?我在文档中看到了 $ rename 运算符,但是我不清楚如何指定一个子字段.

Is there an easy way to rename the field "additional" to "last" in all documents? I saw the $rename operator in the documentation but I'm not really clear on how to specify a subfield.

推荐答案

您可以使用:

db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true);

或者只更新包含该属性的文档:

Or to just update the docs which contain the property:

db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true);

上述方法中的false, true是:{ upsert:false, multi:true }.您需要multi:true来更新所有您的记录.

The false, true in the method above are: { upsert:false, multi:true }. You need the multi:true to update all your records.

或者您可以使用前一种方式:

Or you can use the former way:

remap = function (x) {
  if (x.additional){
    db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});
  }
}

db.foo.find().forEach(remap);

在MongoDB 3.2中,您也可以使用

db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )

一般语法是

db.collection.updateMany(filter, update, options)

https://docs.mongodb.com/manual/reference /method/db.collection.updateMany/

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

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