简体   繁体   中英

MongoDB aggregation query on nested Json array objects

I have a MongoDB and I want to query the database on some values and add them together where a condition matches.

Here is my Collection entry:

{
"_id" : ObjectId("5875ed1dc939408da0601f31"),
"AlbumName" : "Blurryface",
"Group" : "21 Pilots",
"Date" : "20151110",
"Label" : "Fueled By Ramen",
"Writers" : "Tyler Joseph",
"Producer" : "Mike Elizondo",
"Songlist" : [ 
    {
        "_id" : ObjectId("5875e5e8c939408da0601d73"),
        "SongID" : "1",
        "SongName" : "Stressed Out",
        "Artist" : "21 Pilots",
        "Duration:" : "200",
        "nPlays" : "800000000",
        "SongDataFile" : "data"
    }
]
}

I match AlbumName and want to get the nPlays for all(if there are more) songs in "Songlist"

db.Albums.aggregate([
    {$match: {AlbumName: 'Blurryface'}},
    {$unwind: '$Songlist'},
])

However now I can't find out how I get the nPlays from the songs in the array and how I can use them for other things.

How do I get nPlays with MongoDB aggregation?

You could use the $group stage to group the aggregate by the id of the SongList item, something similar to below:

db.Albums.aggregate([
    {$match: {AlbumName: 'Blurryface'}},
    {$unwind: '$Songlist'},
    {$group: {
        _id: '$_id',
        nPlays: {$first: '$nPlays'}
       }
     }
])

This will group the items by the Song _id, which should result in an array of individual songs and their nPlays. See $group

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