Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB:寻找文字,然后计算巧合_Mongodb_Mongodb Query_Aggregation Framework - Fatal编程技术网

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
    所有类型的
    [“幻想”、“戏剧”]
    阵列
  • $group
    按null排序,使用
    $toUpper
    转换为大写后生成标题数组,使用
    $avg
    获取平均年份,使用
    $sum
    获取计数

谢谢!它工作得很好。有什么方法可以使平均年份成为整数?如果我没有错,我可以在整数中看到它,对于类型转换,您可以使用
$toInt
运算符。