Du kan prova nedanstående aggregering
$facet
ger dig de två lägsta och högsta värdena för usages
och du kan enkelt $project
genom dem med $filter
operatör
db.collection.aggregate([
{ "$facet": {
"minUsages": [{ "$sort": { "usages": -1 } }],
"maxUsages": [{ "$sort": { "usages": 1 } }]
}},
{ "$addFields": {
"lowestUsages": {
"$arrayElemAt": ["$minUsages", 0]
},
"highestUsages": {
"$arrayElemAt": ["$maxUsages", 0]
}
}},
{ "$project": {
"minUsages": {
"$filter": {
"input": "$minUsages",
"as": "minUsage",
"cond": {
"$eq": ["$$minUsage.usages", "$lowestUsages.usages"]
}
}
},
"maxUsages": {
"$filter": {
"input": "$maxUsages",
"as": "maxUsage",
"cond": {
"$eq": ["$$maxUsage.usages", "$highestUsages.usages"]
}
}
}
}}
])
Eller så kan du helt enkelt göra detta med find
fråga också
const minUsage = await db.collection.find({}).sort({ "usages": -1 }).limit(1)
const maxUsage = await db.collection.find({}).sort({ "usages": 1 }).limit(1)
const minUsages = await db.collection.find({ "usages": { "$in": [minUsages[0].usages] } })
const maxUsages = await db.collection.find({ "usages": { "$in": [maxUsages[0].usages] } })
Ta en titt här