mongodb 对文档字段的重命名 $rename

$rename

可用于对文档字段的重命名。

使用方式:

{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }

使用实例:

students集合的文档:

{
  "_id": 1,
  "alias": [ "The American Cincinnatus", "The American Fabius" ],
  "mobile": "555-555-5555",
  "name": { "first" : "george", "last" : "washington" },
  "friend": [
		{"first" : "zhang", "last" : "san"},
		{"first" : "li", "last" : "si"}
	]
}

{
  "_id": 2,
  "alias": [ "My dearest friend" ],
  "mobile": "222-222-2222",
  "name": { "first" : "abigail", "last" : "adams" },
  "friend": [
		{"first" : "zhang", "last" : "san"},
		{"first" : "li", "last" : "si"}
	]
}

{
  "_id": 3,
  "alias": [ "Amazing grace" ],
  "mobile": "111-111-1111",
  "name": { "first" : "grace", "last" : "hopper" },
  "friend": [
		{"first" : "zhang", "last" : "san"},
		{"first" : "li", "last" : "si"}
	]
}

对students集合所有文档的nam字段更改为name,name.first字段更改为name.firstName,如下

db.getCollection('students').updateMany({},{$rename:{
    "nam":"name",
    "name.first":"name.firstName"
}});
注!!!

$rename对于数组内对象的key值暂无法更改

例如:friend数组内的first字段无法通过$rename变更。

变更数组内对象的key值

但数组内对象的key值可以通过遍历进行修改

例如下面的语句:

db.getCollection('students').find({}).forEach( function(item){
		for(let i = 0; i<item["friend"].length; i++){
			item["friend"][i].firstName = item["friend"][i].first;
			delete item["friend"][i].first;
		}
		db.getCollection('students').update({"_id":item["_id]}, item);
	}
)

这样就可以将friend数组内的first字段变更为firstName字段。

!!!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值