Let’s say I have a collection:
[
{
_id: product_a,
values: [
{ id: 1, value: 0 },
{ id: 2, value: 1 },
{ id: 3, value: 2 },
]
},
{
_id: product_b,
values: [
{ id: 1, value: 1 },
{ id: 2, value: 2 },
{ id: 3, value: 2 },
]
},
// etc ...
];
Is there any way to query this collection by aggregating the product of a sub-set of “values”?
If I query { values: [ 1, 3 ] }, I would get something like:
[
{
_id: product_a,
result: 0 // since 0 * 2 = 0
},
{
_id: product_b,
result: 2 // since 1 * 2 = 2
},
// etc ...
];
Here is how you can do it with the schema the way you have it using 2.2 aggregation framework. Note that this would be a lot simpler if the id/value pairs were stored with id as key.
Your aggregation pipeline:
Note that the last step would do the job if the structure of your document was:
{_id: "product_x", values: [ {id1: value}, {id2: value} etc. ]}Now run the query from the shell with:
> db.collection.aggregate(pipeline)Or from your code via
db.runCommand({"aggregate":"collection","pipeline":[...]})