0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I tried your solution but it did not worked. I think you did not notice that my tech subdocument is an array of objects, so tech.size or tech.color is not accessible directly.
@FredMériot Don't know how that was missed in typing. See the edit. You need to filter in this particular case. There is another way to do this with the $cond operator as well
@FredMériot did you miss the edit comment. What about this does not meet your needs?
No, I did not succeed to make it works. I still have the problem with the $tech.value in the group directive.
@FredMériot possibly more typing mistakes but I do not see the problem in general. The statement works perfectly fine for me. Check the edit again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.