How to move Embedded Fields out of their embedded document?


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.





not clear what you are trying to do here... please clarify your question
– Anthony Winzlet
Jun 30 at 1:47





I changed it a little for you @AnthonyWinzlet. I am trying to move "Artist" field to be outside the "details" document but the "Album" and "ReleaseYear" should stay within that document. I know it's a basic query, but I've only been learning MongoDB for a few days.
– andrewtalle
Jun 30 at 3:04






Ok so do you want to update your document or need to get something like that?
– Anthony Winzlet
Jun 30 at 5:25




1 Answer
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.


$rename



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:


discography


Details.Artist


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"
}





This is it!! Thank you so much @stennie! Now I thik dot notation is starting to make more sense to me.
– andrewtalle
2 days ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift