0

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?

2
  • I figured it out by trial and error. I added this under unwind: {$project: {nPlays: '$Songlist.nPlays'}} Commented Jan 11, 2017 at 15:02
  • Hello. If you found the answer yourself you can post it as an answer and accept it. Commented Jan 11, 2017 at 15:10

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

What if i wat to match by SongName with this example can we search and pull with that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.