简体   繁体   中英

Renaming a field in an embedded Document in an Array in MongoDB not working

Step One

> db.myCollection.find();
{ "_id" : ObjectId("2358523892345"), "field1" : "value 1", "field2" : [ { "subfield1" : "value 2" }, { "Subfield2" : "value 3" } ], "field3" : "value 4" }

I am wanting to rename the field Subfield2 to subfield2 . I tried:

Step Two

> db.myCollection.update ( { "field3": "value 4" }, {$rename: {"Subfield2": "subfield2" } } )

And then ran find() again and get the same results as in 'Step One' ie the field is not renamed.

Using MongoDB terminology, I think what I am trying to do is 'rename a field in an embedded document in an array'.

References

http://docs.mongodb.org/manual/reference/operator/rename/

It seems to not be possible to rename a field within an array from the command line as answered in this question:

MongoDB rename database field within array

As mentioned in the documentation there is no way to rename fields within arrays. Your only option is to iterate over your collection documents, read them and update each with $unset old/$set new operations.

It is possible to change these values via RockMongo however as suggested by user Liad Livnat.

For my particular instance, whist there I also removed the array and changed the structure to:

{
  "field1": "value 1",
  "field2": {"subfield1": "value 2", "subfield2": "value 3"},
  "field3": "value 4"
}

Querying this object was then possible with:

db.myCollection.find( {"field2.subfield2":"value 3"} );

if you want to update it manually i suggest you will install rockmongo, rockmongo is a great tool working with mongo databases, just extract it on your server and connect to your database. there you will find very easy update to mongo database, tables and records.

rock mongo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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