[英]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. 我有一个MongoDB,我想查询一些值的数据库,并将它们添加到条件匹配的地方。
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" 我匹配AlbumName,并希望获取“歌曲列表”中所有(如果有更多歌曲)的nPlay
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. 但是现在我不知道如何从数组中的歌曲中获取nPlay,以及如何将它们用于其他用途。
How do I get nPlays with MongoDB aggregation? 如何通过MongoDB聚合获取nPlay?
You could use the $group stage to group the aggregate by the id of the SongList item, something similar to below: 您可以使用$ group阶段按SongList项目的ID对汇总进行分组,如下所示:
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. 这将按照Song _id对项目进行分组,这将导致单个歌曲及其nPlay的数组。 See $group 查看$ group
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.