MongoDB:寻找文字,然后计算巧合
我有一个图书数据库,如下所示:MongoDB:寻找文字,然后计算巧合,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我有一个图书数据库,如下所示: {"_id": ObjectID("1"), "title": "Harry Potter", "year": NumberInt(2000), "author": "JK. Rowling", "genres" : [fantasy, drama]}, {"_id": ObjectI
{"_id": ObjectID("1"), "title": "Harry Potter", "year": NumberInt(2000), "author": "JK. Rowling", "genres" : [fantasy, drama]},
{"_id": ObjectID("2"), "title": "Harry Potter 99", "year": NumberInt(2020), "author": "JK. Rowling", "genres" : [fantasy, drama]},
{"_id": ObjectID("3"), "title": "Book", "year": NumberInt(2020), "author": "Mr. Author", "genres" : [war, romance]},
{...}
{
"_id" : ["HARRY POTTER", "HARRY POTTER 99],
"yearavg" : "2010",
"count" : "2"
}
我想得到结合了“幻想”和“戏剧”两种类型的书籍,将它们的标题转换为大写字母,计算它们的数量,最后得到它们出版年份的平均值。大概是这样的:
{"_id": ObjectID("1"), "title": "Harry Potter", "year": NumberInt(2000), "author": "JK. Rowling", "genres" : [fantasy, drama]},
{"_id": ObjectID("2"), "title": "Harry Potter 99", "year": NumberInt(2020), "author": "JK. Rowling", "genres" : [fantasy, drama]},
{"_id": ObjectID("3"), "title": "Book", "year": NumberInt(2020), "author": "Mr. Author", "genres" : [war, romance]},
{...}
{
"_id" : ["HARRY POTTER", "HARRY POTTER 99],
"yearavg" : "2010",
"count" : "2"
}
我无法通过分组,所以我写了这篇文章,但它不起作用:
query1 = {"genres" : "Fantasy"}
query2 = {"genres" : "Drama"}
logic = {$and : [query1, query2]}
phase1 = {$match : logic}
phase2 = {$group : {"_id" : "$title", "year" : "$year"}}
phase3 = {$project : {"total" : {"$size" : "$genres"}, "genres" : 1}}
steps = [phase1, phase2, phase3]
db.genres.aggregate(steps)
谢谢 你可以试试
所有类型的$match
阵列[“幻想”、“戏剧”]
按null排序,使用$group
转换为大写后生成标题数组,使用$toUpper
获取平均年份,使用$avg
获取计数$sum
谢谢!它工作得很好。有什么方法可以使平均年份成为整数?如果我没有错,我可以在整数中看到它,对于类型转换,您可以使用
$toInt
运算符。