Du kan prøve nedenstående aggregering
$facet
vil give dig de to laveste og højeste værdier for usages
og du kan nemt $project
gennem dem ved hjælp af $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 du kan simpelthen gøre dette med find
forespørgsel også
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] } })
Tag et kig her