Fred Mériot
Fred Mériot

Reputation: 4357

MongoDB aggregation : $sum values of a key in a collection

I have a mongodb collection full of documents like this :

{
    _id : xxxxxx
    category : 1,
    tech : [
        {key:"size",value:5},
        {key:"color",value:"red"}
        {key:"weight",value:27.4}
    ]
}

My question is : how can I do to aggregate (average, sum or whatever) each item with key = "size" in this collection?

thank you for your help

Upvotes: 0

Views: 2833

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151180

When you have documents that contain an array you use the $unwind operator in order to access the array elements.

db.tech.aggregate([
    { "$unwind": "$tech" },
    { "$match": { "tech.key": "size" } },
    { "$group": { 
        "_id": null,
        "totalSize": { "$sum": "$tech.value" }
    }}
])

So once the array is "un-wound" you can then $group on whatever you want to use as a key under the _id field, for all documents in the collection use null. Any of the group aggregation operators can be applied.

The array elements in the "de-normalized" documents will be available through "dot notation" as shown above.

Also see the full list of aggregation operators in the manual.

Upvotes: 2

Related Questions