简体   繁体   English

在 MongoDB 中使用 $rename 重命名嵌套字段名称

[英]Rename nested field name using $rename in MongoDB

I am new at learning MongoDB and I want to rename the "ratings" array of the "Jimmy" customer in the following:我是学习 MongoDB 的新手,我想将“Jimmy”客户的“评级”数组重命名如下:

{ 
   "CUSTOMER" : 
         { 
           "first name" : "Jimmy",
           "ratings" : [ 
                    { "increase" : { "rate" : 99 } }, 
                    { "increase" : { "rate2" : 20.5 } 
                  } 
            ] 
      } 
}

I have tried many ways such as我尝试了很多方法,例如

db.collection.update({"CUSTOMER.first name":"Jimmy"}, {$rename:{"CUSTOMER.ratings":"discountings"}});

This way separate the array and make it as a new customer.这种方式将阵列分离并使其成为新客户。 Meaning that the array goes out of the CUSTOMER document.这意味着该数组超出了 CUSTOMER 文档。 Also, I did put the $ symbol prior to "ratings" and I know it is not the right way and in fact it gives error message "not be dynamic".此外,我确实将 $ 符号放在“评级”之前,我知道这不是正确的方式,实际上它给出了错误消息“不是动态的”。

Also, I tried the following, but actually it is not right as we are asking as if we want to change the entire document name.另外,我尝试了以下方法,但实际上这是不正确的,因为我们询问是否要更改整个文档名称。 It give error message "must be a string".它给出错误消息“必须是一个字符串”。

db.collection.update({"CUSTOMER.first name":"Jimmy"}, {$rename:{"CUSTOMER":{"ratings":"discountings"}});

To sum up, it is wanted to change "ratings" to "discountings".综上所述,就是想把“评分”改成“折扣”。

Since you're renaming embedded document, you need to use .由于您要重命名嵌入式文档,因此您需要使用. notation not only in key but also in value .符号不仅在key中,而且在value中。

db.collection.update({"CUSTOMER.first name":"Jimmy"}, {$rename:{"CUSTOMER.ratings":"CUSTOMER.discountings"}})

If you don't use .如果你不使用. notation:符号:

db.collection.update({"CUSTOMER.first name":"Jimmy"}, {$rename:{"CUSTOMER.ratings":"discountings"}});

then it would { $unset: {'CUSTOMER.ratings': 1} } and { $set: {'discountings': '$CUSTOMER.ratings'} }那么它会{ $unset: {'CUSTOMER.ratings': 1} }{ $set: {'discountings': '$CUSTOMER.ratings'} }

Ref: $rename参考: $重命名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM