我有具有这种简化架构的文档:
{
positon: 10,
value: 5,
count: 3
}
我想要计算的是按位置
对这些文档进行分组,并找到最大值
,其中计数大于4但具有值
小于计数小于 4 的最小值
。
这是我所做的,但它不起作用:
{ $group: {
_id: {
position: "$position",
},
result: {$max: { $cond: [ {$and: [ {$gte: ["$count", 4]},
{$lt: ["$value", {$min: { $cond: [ {$lt: ["$count", 4]},
{ value: "$value" },
10]
}
}]
}]},
{ value: "$value", nb: "$count"},
0]
}
}
}
}
有人说 $min
是一个无效的运算符,我不知道如何编写正确的聚合函数。运行mapreduce会更好吗?
如果我有这些文件
{Position: 10, value: 1, count 5}
{Position: 10, value: 3, count 3}
{Position: 10, value: 4, count 5}
{Position: 10, value: 7, count 4}
我希望结果是
{Position: 10, value: 1, count 4}
因为它是计数大于 4 的“值”的最大值,而且因为值 3 只有 3 个计数,所以值 4 不是我要查找的值。
最佳答案
至少可以说这有点拗口,但我会再解释一下:
你想要:
For each "Position" value find the document whose "value" is less than the the largest "value" of the document with a "count" of less than four, whose own "count" is actually greater than 4.
这读起来就像一道数学考试题,旨在让你混淆逻辑。但是,捕获这个含义之后,您可以通过以下步骤执行聚合:
db.positions.aggregate([
// Separate the values greater than and less than 4 by "Position"
{ "$group": {
"_id": "$Position",
"high": { "$push": {
"$cond": [
{ "$gt": ["$count", 4] },
{ "value": "$value", "count": "$count" },
null
]
}},
"low": { "$push": {
"$cond": [
{ "$lt": ["$count", 4] },
{ "value": "$value", "count": "$count" },
null
]
}}
}},
// Unwind the "low" counts array
{ "$unwind": "$low" },
// Find the "$max" value from the low counts
{ "$group": {
"_id": "$_id",
"high": { "$first": "$high" },
"low": { "$min": "$low.value" }
}},
// Unwind the "high" counts array
{ "$unwind": "$high" },
// Compare the value to the "low" value to see if it is less than
{ "$project": {
"high": 1,
"lower": { "$lt": [ "$high.value", "$low" ] }
}},
// Sorting, $max won't work over multiple values. Want the document.
{ "$sort": { "lower": -1, "high.value": -1 } },
// Group, get the highest order document which was on top
{ "$group": {
"_id": "$_id",
"value": { "$first": "$high.value" },
"count": { "$first": "$high.count" }
}}
])
因此,从一组文档来看:
{ "Position" : 10, "value" : 1, "count" : 5 }
{ "Position" : 10, "value" : 3, "count" : 3 }
{ "Position" : 10, "value" : 4, "count" : 5 }
{ "Position" : 10, "value" : 7, "count" : 4 }
在这种情况下,仅返回第一个,因为它的值小于“计数三”文档,而它自己的计数大于 4。
{ "_id" : 10, "value" : 1, "count" : 5 }
我确信这就是您的实际意思。
所以$min
的应用和 $max
实际上仅适用于从分组范围之外的文档中获取离散值时。如果您对文档或整个文档中的多个值感兴趣,那么您将排序并获得 $first
或$last
分组边界上的条目。
聚合比 mapReduce 快得多,因为它使用 native 代码而不调用 JavaScript 解释器。
关于MongoDB 最小/最大聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23208818/