Aki
Aki

Reputation: 33

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:

{ 
   "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. 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".

Upvotes: 1

Views: 881

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Since you're renaming embedded document, you need to use . notation not only in key but also in 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'} }

Ref : $rename

Upvotes: 2

Related Questions