I'm currently facing a challenge with executing a query to retrieve only the MIN and MAX values for a specific field within an Array field...
The field client.files.uploads
is the target for fetching the MIN/MAX values.
The desired result should be something like "0,10
", where I aim to extract just the lowest and highest values of uploads from all client
entries without returning multiple fields or rows for each client.
Below is my initial query which did not provide the expected outcome:
db.client.aggregate([
{$unwind: "$files"},
{
$group: {
_id : "$_id",
data_min: {$min: "$files.uploads"},
data_max: {$max: "$files.uploads"}
}
},
{
$project:{
data_min: "$min",
data_max: "$max",
}
}
],{allowDiskUse:true})
UPDATE:
I have successfully achieved the desired result using a different approach, but I still believe there might be a more efficient way to accomplish this task:
db.clients.aggregate([
{$unwind: "$files"},
{
$group: {
_id: "$_id",
data_min: {$min: "$files.uploads"},
data_max: {$max: "$files.uploads"}
}
},
{
$group: {
_id: "1",
min: {$min: "$data_min"},
max: {$max: "$data_max"}
}
},
{
$project: {
_id: 0,
min: 1,
max: 1
}
}
],
{
allowDiskUse: true
})
This modified query now returns a single row containing the minimum and maximum values for the entire collection, meeting the original objective.
Here is an example dataset based on my documents:
[
{
"name": "John",
"files": [
{
"uploads": 9685,
"downloads": 83,
},
{
"uploads": 1,
"downloads": 833
},
{
"uploads": 676,
"downloads": 823
}
]
},
{
"name": "Peter",
"files": [
{
"uploads": 32,
"downloads": 99
},
{
"uploads": 34,
"downloads": 4
}
]
},
{
"name": "Mery",
"files": [
{
"uploads": 3,
"downloads": 244
},
{
"uploads": 15,
"downloads": 543
},
{
"uploads": 1345,
"downloads": 22
},
{
"uploads": 6743,
"downloads": 87543
}
]
}
]