MongoDB聚合:我想从电影中提取最昂贵的类型,我能够计算该类型,但我无法提取它的标题



MongoDB聚合:我想从电影中提取最昂贵的类型,我能够计算该类型,但我无法提取它的标题

Movie.aggregate([
{
$unwind: '$genre'
}, {
$group: {
_id: "$genre",
numOfMovies: {$sum: 1},
// movieTitles: { $push: '$title'}
genrePrice: { $sum: '$price' },
}
},
{
$group: {
_id: '$_id',
topPricedGenre: {$max: '$genrePrice'},
}
}

]);

通过使用上面的查询,我可以提取最昂贵的类型,但我也想提取它的标题.....我得到这样的输出:

{
"status": "success",
"lenght": 20,
"data": [
{
"_id": "Musical",
"topPricedGenre": 75201
},
{
"_id": "Fantasy",
"topPricedGenre": 100296
},
{
"_id": "Documentary",
"topPricedGenre": 167574
},
{
"_id": "War",
"topPricedGenre": 88227
},
{
"_id": "(no genres listed)",
"topPricedGenre": 6375
},
{
"_id": "Western",
"topPricedGenre": 52622
},
{
"_id": "Children",
"topPricedGenre": 54527
},
{
"_id": "Mystery",
"topPricedGenre": 102575
},
{
"_id": "Crime",
"topPricedGenre": 141468
},
{
"_id": "Comedy",
"topPricedGenre": 456751
},
{
"_id": "Horror",
"topPricedGenre": 181037
},
{
"_id": "Sci-Fi",
"topPricedGenre": 100986
},
{
"_id": "Drama",
"topPricedGenre": 796831
},
{
"_id": "Action",
"topPricedGenre": 212681
},
{
"_id": "Film-Noir",
"topPricedGenre": 16103
},
{
"_id": "Adventure",
"topPricedGenre": 132670
},
{
"_id": "Romance",
"topPricedGenre": 267585
},
{
"_id": "IMAX",
"topPricedGenre": 9471
},
{
"_id": "Animation",
"topPricedGenre": 46687
},
{
"_id": "Thriller",
"topPricedGenre": 245489
}
]
}

我正期待着这个结果,谁能帮帮我吗?

{
"_id": "Drama",
"topPricedGenre": 796831
}

MongoDB可以比较的文档也可以看这个

使用像下面这样的累加器将保留电影的最大价格和标题。这就像获得最大价格,首先,只有当2部电影等于最大价格,然后获得最大标题。

如果你试了,问题发生了,如果你能给出初始数据,所以我们可以测试并给出一个完整的查询。

{$max: {"maxPrice" : "$genrePrice"
"title" :"$title"}}

最新更新