I have an aggregation pipeline that groups objects and holds count for some specific field for grouped objects. You can reproduce the problem here: https://mongoplayground.net/p/2DGaiQDYDBP .
The schema is like this;
[
{
"_id": {
"$oid": "63ce93ffb6e06322db59fdc0"
},
"fruit": "apple",
"source": "tree",
"is_fruit_important": "true"
},
{
"_id": {
"$oid": "63ce93ffb6e06322db59fdc1"
},
"fruit": "orange",
"source": "tree",
"is_fruit_important": "false"
},
]
and the current query groups fruits by the source, and holds the count of important fruits for every group. After applying aggregation I get something like this after query:
[
{
"count": {
"number_of_important_fruits": 1
},
"objects": [
{
"fruit": "apple",
"id": "63ce93ffb6e06322db59fdc0",
"is_fruit_important": "true",
"source": "tree"
},
{
"fruit": "orange",
"id": "63ce93ffb6e06322db59fdc1",
"is_fruit_important": "false",
"source": "tree"
}
],
"source": {
"source-of": "tree"
}
}
]
Is there a way to put the number of all fruits in the database to the response object. For example like this:
{
"total-count": 2,
"result": [
{
"count": {
"number_of_important_fruits": 1
},
"objects": [
{
"fruit": "apple",
"id": "63ce93ffb6e06322db59fdc0",
"is_fruit_important": "true",
"source": "tree"
},
{
"fruit": "orange",
"id": "63ce93ffb6e06322db59fdc1",
"is_fruit_important": "false",
"source": "tree"
}
],
"source": {
"source-of": "tree"
}
}
]
}
They can be handled in separate aggregation pipelines but that’s what I would not like to implement. Any help would be highly appreciated.
2
Answers
You can simply add a
$facet
stage to push all your results intoresult
. Then perform a$size
onresult
to gettotal-count
.Mongo Playground
Add one additional group stage just before the final $project, using
$sum
with$size
for a total count, or add up the important counts for a total important count.Playground