I am trying to write a query to group my records by the value inside an array inside another array inside a collection in MongoDB. Now if that doesn't have your head hurting I think a sample schema might be easier to understand:
{
"_id": ObjectId("...")
"attributes": [
[ "attributeA", "valueA" ],
[ "attributeB", "valueB" ],
[ "attributeC", "valueC" ],
...
]
}
Now I want to be able to group my records by the attributeB field based on valueB.
So far I can aggregate if I know the actual value of valueB:
collection.aggregate([
{ '$match': { 'attributes': [ "attributeB", "valueB" ] } },
{ '$group': {
'_id': { 'attributes': [ "attributeB", "valueB" ] } }
}
])
Basically seeing if the attributes array contains the pair: [ "attributeB", "valueB" ]. But now I want to be able to have the query determine what valueB is as it performs the aggregation.
To paraphrase: I can't seem to figure out how to group by the value if I don't know the value of valueB. I just want all records to group by their valueB's, when attributeB is found at the first position inside an array inside the attributes array.
Any help is appreciated. Thanks!
[{"attributeA":"valueA"},{"attributeB":"valueB"}]or"attributes":{"attributeA":"valueA","attributeB":"valueB"}? It would make querying a lot easier.