假设我有一个文档结构,其中一个字段X
是一个数组av对象,如下所示。
"X" : [
{
"A" : "abc",
"B" : 123
},
{
"A" : "wer",
"B" : 124
},
{
"A" : "fgh",
"B" : 124
}
]
如何仅将B
字段值最高的文档投影?如果最大值由多个文档共享,我只想返回其中一个(不重要的是哪个)。在这种情况下,结果可能类似于:
"X" : [
{
"A" : "wer",
"B" : 124
}
]
答案 0 :(得分:2)
那一个呢?
db.collection.aggregate([
{
$set: {
X: {
$filter: {
input: "$X",
cond: { $eq: ["$$this.B", { $max: "$X.B" }] }
}
}
}
},
{ $set: { X: { $arrayElemAt: ["$X", 0] } } }
])
答案 1 :(得分:1)
您可以使用$reduce
db.collection.aggregate([
{
"$project": {
"X": {
$reduce: {
input: "$X",
initialValue: {},
in: {
$cond: [ { "$gt": [ "$$this.B", "$$value.B" ]}, // Condition Check
"$$this", // If condition true ($$this - Current Object)
"$$value" // If condition false $$value - Previous Returned Object
]
}
}
}
}
}
])
答案 2 :(得分:0)
最新答案:
另一个导致最终返回完整对象的选项:
[
{$unwind: {
path: "$X"
}},
{$sort: {
"X.B": -1
}},
{$group: {
_id: { _id: "$_id"},
X: {
$first: "$X"
}
}}]
原始答案:
您可以使用$ max运算符(https://docs.mongodb.com/manual/reference/operator/aggregation/max/)。
[{$project: {
X: {$max: "$X.B"}
}}]