'How to move Embedded Fields out of their embedded document?

Here is an example of one of my JSON docs:

{
    "_id": 1,
    "SongId": 1,
    "Details": {
        "Artist": "Cyndi Lauper",
        "Album": "She's So Unusual",
        "ReleaseYear": 1983
    },
    "SongTitle": "Girls Just Want To Have Fun"
}

How would one write a query to move the location of "Artist" and it's value out of the "Details" document, leaving "Album" & "ReleaseYear" still embedded.



Solution 1:[1]

In addition to updating the name of a field, the $rename operator can be used to move fields out of (or into) embedded documents.

When working with fields in embedded documents you need to use dot notation to refer to the field name.

Assuming a collection name of discography, you could move your Details.Artist field using:

db.discography.update(
    {_id: 1},
    {$rename: { "Details.Artist": "Artist"}}
)

Example result:

> db.discography.findOne({_id: 1})
{
    "_id" : 1,
    "SongId" : 1,
    "Details" : {
        "Album" : "She's So Unusual",
        "ReleaseYear" : 1983
    },
    "SongTitle" : "Girls Just Want To Have Fun",
    "Artist" : "Cyndi Lauper"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stennie