我有这个问题。考虑到我们有许多关于电影和发行年份的文档。下面是一个文档示例:
{
"_id" : ObjectId("63a994974ac549c5ea982d2b"),
"title" : "Destroyer",
"year" : 2018
},
{
"_id" : ObjectId("63a994974ac549c5ea982d2a"),
"title" : "Aquaman",
"year" : 2014
},
{
"_id" : ObjectId("63a994974ac549c5ea982d29"),
"title" : "On the Basis of Sex",
"year" : 1998
},
{
"_id" : ObjectId("63a994974ac549c5ea982d28"),
"title" : "Holmes and Watson",
"year" : 1940
},
{
"_id" : ObjectId("63a994974ac549c5ea982d27"),
"title" : "Conundrum: Secrets Among Friends",
"year" : 1957
},
{
"_id" : ObjectId("63a994974ac549c5ea982d26"),
"title" : "Welcome to Marwen",
"year" : 2000
},
{
"_id" : ObjectId("63a994974ac549c5ea982d25"),
"title" : "Mary Poppins Returns",
"year" : 1997
},
{
"_id" : ObjectId("63a994974ac549c5ea982d24"),
"title" : "Bumblebee",
"year" : 2018
},
因此,我想计算在文档中注册的最大年份和20年前(即2018年和1998年)之间的电影。
我的尝试如下:
var query1 = {"$addFields": {maxium: {$max: "$year"}, minimum : {$subtract: [{$max: "$year"}, 20]}}}
var filter = {"year": {"$lte": maximum, "$gte": minimum}}
var logic = {$match: {$and: [filter]}}
var query1 = {$group: {"_id": null, "count": {$sum:1}}}
var stage = [logic, query1]
db.movies.aggregate(stage)
但是我不能得到正确的输出。我得到的是以下输出:
{
"message" : "maximum is not defined",
"stack" : "script:3:32"
}
我不知道我做错了什么。对于前面的例子,这将是正确的输出:
"_id": null,
"count": 4
我该如何解决这个问题?我怎样才能动态地计算年份之间的所有电影,即使用$max和$subtract…?
致以最亲切的问候!谢谢! !
为了获得最大的year
,您需要对文档进行分组或使用$setWindowFields
来比较它们。一种选择是使用$setWindowFields
,它允许您避免将所有文档分组为一个大文档,因为文档有大小限制:
db.collection.aggregate([
{$setWindowFields: {
sortBy: {year: -1},
output: {
maxYear: {
$max: "$year",
window: {documents: ["unbounded", "current"]}
}
}
}},
{$match: {$expr: {$lt: [{$subtract: ["$maxYear", "$year"]}, 20]}}},
{$group: {_id: 0, count: {$sum: 1}}}
])
看看它在操场的例子中是如何工作的