I have a mongodb query that looks like the following:
[
{$facet: {
subpipeline1: [
{$match: { ...
// mongo subpipeline 1 query
}
]
, subpipeline2: [
{$match: { ...
// mongo subpipeline 2 query
}
]
}}
]
result of subpipeline1 is:
_id qty
category_1 qty_1
result of subpipeline2 is:
_id qty
category_all qty_all
I want to divide qty_1
(qty
from subpipeline1) by qty_all
(qty
from subpipeline2)
Seeking the help of the community to guide me please.
Takis
(Takis )
November 30, 2021, 2:04am
#2
Results of each subpipeline will be array of documents, if you can give sample data of the results in JSON, and what is the expected output you need. Maybe $map
can help you. But if you give sample data it will be helpful alot.
Hi Takis, many thanks for your attention to my question. I intend to do the following please -
The result of subpipeline1 is the following
[
{_id: 'category_1', qty: '10'},
{_id: 'category_2', qty: '15'},
{_id: 'category_3', qty: '35'},
{_id: 'category_4', qty: '50'}
]
The result of subpipeline2 is the following
[
{_id: 'category_all', qty: '110'}
]
Combining the above 2, I intend to get the following output:
[
{_id: 'category_1', qty: '10', total: '110'},
{_id: 'category_2', qty: '15', total: '110'},
{_id: 'category_3', qty: '35', total: '110'},
{_id: 'category_4', qty: '50', total: '110'}
]
Many thanks for your guidance.
Takis
(Takis )
December 1, 2021, 3:06pm
#4
Data (after the $facet)
[
{
"subpipeline1": [
{
"_id": "category_1",
"qty": "10"
},
{
"_id": "category_2",
"qty": "15"
},
{
"_id": "category_3",
"qty": "35"
},
{
"_id": "category_4",
"qty": "50"
}
],
"subpipeline2": [
{
"_id": "category_all",
"qty": "110"
}
]
}
]
Query
aggregate(
[{"$unwind": {"path": "$subpipeline1"}},
{"$project":
{"_id": "$subpipeline1._id",
"qty": "$subpipeline1.qty",
"total": {"$arrayElemAt": ["$subpipeline2.qty", 0]}}}])
Data out
[{
"_id": "category_1",
"qty": "10",
"total": "110"
},
{
"_id": "category_2",
"qty": "15",
"total": "110"
},
{
"_id": "category_3",
"qty": "35",
"total": "110"
},
{
"_id": "category_4",
"qty": "50",
"total": "110"
}]