0

How to count and sum the same value of size where stock is equal to 'Available' in one of mongodb collection.

desired result as below:

{_id :'S',count: 5 },
{_id :'M',count: 2 },
{_id :'L',count: 1 }
"price" : 123.8,
"gender" : "women",
"colour" : "blue",
"item" : [ 
    {
        "name" : "ICE DUO ANTHRACITE YELLOW SMALL (S)",
        "size" : "S",
        "stock" : "Available",
        "_id" : ObjectId("59b2829e5acd8e2d14aa84cf")
    }, 
    {
        "name" : "ICE DUO ANTHRACITE YELLOW SMALL (L)",
        "size" : "L",
        "stock" : "Available",
        "_id" : ObjectId("59b2829e5acd8e2d14aa84ce")
    }, 
    {
        "name" : "ICE DUO ANTHRACITE YELLOW SMALL (M)",
        "size" : "M",
        "stock" : "Available",
        "_id" : ObjectId("59b2829e5acd8e2d14aa84cd")
    }
],

1 Answer 1

1

Try below:

db.users.aggregate([
{$match:{stock:'Available'}},
{$unwind: 'item'},
{$group:{_id: '$size', count:{$sum:1}}}
])
Sign up to request clarification or add additional context in comments.

7 Comments

I had already tried this code but I didn't get my desired result.
So what are you getting after executing it?
Besides that, I still want to match with stock = 'Available'
I will edit my answer for available condition. BT Please write ur complete requirement in the question.
After I added some code like { $project: { item: 1 } } I able to get result like [ { _id: 'M', count: 2 }, { _id: 'L', count: 3 }, { _id: 'S', count: 2 } ] But the result is wrong because still doesn't do checking to count out all the size which match with stock='Available'
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.