如何在数组中找到数组的最大值?
How to find max value of an array inside array?
mongodb数据库中的数据结构如下:
{
"date": "20201005",
"data":[
[10, 20, 30, 40, 50],
[60, 70, 80, 90, 10],
[11, 12, 13, 14, 15]
]
}
{
"date": "20201006",
"data":[
[12, 22, 32, 42, 52],
[61, 77, 88, 98, 10],
[11, 12, 13, 14, 15]
]
}
{
"date": "20201007",
"data":[
[11, 21, 31, 41, 51],
[16, 17, 18, 19, 10],
[11, 12, 13, 14, 99]
]
}
并且你想在每个文档中找到数组内部数组的最大值,我想要得到的结果如下:
{"max": 99} // 99 can be find in document where "date"="20201007"
如何使用 $max
运算符做到这一点?
你可以使用
db.collection.aggregate([
{ //Restructure
$unwind: "$data"
},
{
$project: {
"max": {//Max in each array
"$max": "$data"
}
}
},
{
$group: {
"_id": null,
"max": {//Max of whole data
$max: "$max"
}
}
}
])
mongodb数据库中的数据结构如下:
{
"date": "20201005",
"data":[
[10, 20, 30, 40, 50],
[60, 70, 80, 90, 10],
[11, 12, 13, 14, 15]
]
}
{
"date": "20201006",
"data":[
[12, 22, 32, 42, 52],
[61, 77, 88, 98, 10],
[11, 12, 13, 14, 15]
]
}
{
"date": "20201007",
"data":[
[11, 21, 31, 41, 51],
[16, 17, 18, 19, 10],
[11, 12, 13, 14, 99]
]
}
并且你想在每个文档中找到数组内部数组的最大值,我想要得到的结果如下:
{"max": 99} // 99 can be find in document where "date"="20201007"
如何使用 $max
运算符做到这一点?
你可以使用
db.collection.aggregate([
{ //Restructure
$unwind: "$data"
},
{
$project: {
"max": {//Max in each array
"$max": "$data"
}
}
},
{
$group: {
"_id": null,
"max": {//Max of whole data
$max: "$max"
}
}
}
])