'Get min and max value in single query in mongodb
Considering the following Documents in "Words":
[{
_id: 1,
usages: 2,
word: "Name"
}, {
_id: 2,
usages: 1,
word: "Street"
}, {
_id: 3,
usages: 1,
word: "House"
}, {
_id: 4,
usages: 3,
word: "Table"
}, {
_id: 5,
usages: 3,
word: "Bread"
}, {
_id: 6,
usages: 4,
word: "Door"
}]
How can i get all the records where the number of usages is the lowest or highest? Lowest should return id 2 and 3(and their word), highest should return id 6 with its word.
I need to aggregate this data into a random amount of lowest/highest records (50 to be exact) so it needs to be an aggregate.
It should be a single lookup, so the min/max cannot be found using another query with $max or $min.
The MongoDB version is 3.4.7, Mongoose version 5.0.0-rc1. Mongoose solution not requred since I can use a raw query. (It is preferred however!)
Example:
Words.aggregate([
{
$match: { _
usages: { WHAT_SHOULD_I_HAVE_HERE }
}
}, {
$sample: {
size: 50
}
}
])
Thanks!
Solution 1:[1]
Given the following collection MyCollection data:
{ "_id" : ObjectId("ob1"), "value" : 17 }
{ "_id" : ObjectId("ob2"), "value" : 99 }
{ "_id" : ObjectId("ob3"), "value" : 35 }
{ "_id" : ObjectId("ob4"), "value" : 46 }
{ "_id" : ObjectId("ob5"), "value" : 12 }
You can perform the following query:
db.MyCollection.aggregate([
{ "$group": {
"_id": null,
"max_val": { "$max": "$value" },
"min_val": { "$min": "$value" }
}}
]);
And get:
{ "_id" : null, "max_val" : 99, "min_val" : 12 }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hardest |
