【发布时间】:2020-11-13 05:07:30
【问题描述】:
我有一个书单。我想得到作者写的类型的数量,我也想添加这些类型的结果。我的数据库如下所示:
{"_id": ObjectID("1), "title": "Harry Potter", "year": NumberInt(2000), "author": "JK. Rowling",
"genres": "Fantasy"},
"_id": ObjectID("2"), "title": "Harry Potter 99", "year": NumberInt(2020), "author": "JK. Rowling",
"genres": "Drama"}, "_id": ObjectID("2"), "title": "Harry Potter", "year": NumberInt(2000), "author": "JK. Rowling",
"genres": "Drama"}, {...}
所以,到目前为止,我的代码如下所示:
phase1 = {$group : {"_id" : "$author"}, "countgenres" : {$sum : 1}}
phase2 = {$addFields : "genres"}}
phase3 = {$sort : {"numgenres" : -1}}
steps = [phase1, phase2, phase3]
db.database.aggregate(steps)
这对我不起作用,所以我希望有人可以帮助我编写正确的代码来执行此操作。结果应如下所示:
{
"_id" : "JK. Rowling",
"countgenres" : 4,
"genres" : [
"War",
"Fantasy",
"Drama",
"Crime"
]
}
谢谢。
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework