从MongoDB聚合中未命名的嵌套对象数组中获取最大值的键



我有一个文档是这样的。

{
city: "Manhattan",
State: "NY",
eth:[
{02: 40},
{15:50},
{04:10}
]
}

我想做的是在eth数组中找到最大值的对象。我试过这样做。

project:{
{'eth':{$reduce:{
input:"$eth",
initialValue:1,
in:{$max:["$$value","$$this"]}
}}}
,{
$project:{"eth":{$objectToArray:"$eth"}},
}
}

其结果为{k:15,v:60}]。

如何获得k的值作为我的eth。我试着做另一个项目,试图获得"$eth[0].k",但结果是未定义的。

我希望输出看起来像:

{
city: "Manhattan",
state:"NY",
eth: 15
}

您可以简单地使用$max来获得最大值

db.collection.aggregate([
{ "$project": {
"max": {
"$objectToArray": {
"$max": "$eth"
}
}
}},
{ "$project": {
"eth": {
"$arrayElemAt": ["$max.k", 0]
}
}}
])

最新更新