Anda dapat mencoba agregasi di bawah ini
$facet
akan memberi Anda dua nilai terendah dan tertinggi untuk usages
dan Anda dapat dengan mudah $project
melalui mereka menggunakan $filter
operator
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"]
}
}
}
}}
])
Atau Anda bisa melakukannya dengan find
permintaan juga
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] } })
Lihat di sini