Ajouve
Ajouve

Reputation: 10089

Count nested element with a condition MongoDB

I have this data model:

{_id: 1, userId: 1, elements: [{type:'a', startDate: 2015-10-10 20:00:00}]},
{_id: 2, userId: 2, elements: [{type:'b', startDate: 2016-10-10 20:00:00}]},
{_id: 3, userId: 1, elements: [{type:'c', startDate: 2016-10-10 20:00:00}]},
{_id: 4, userId: 1, elements: [{type:'a', startDate: 2016-10-10 20:00:00}]}

I'd like to count all the elements for an user with a condition on the startDate.

for example count the number of element for userId:1 and startDate greater than 2016-10-09 20:00:00

I tried

db.collection.aggregate([
    {'$match': {userId: 1}},
    {$group: {_id: null, elements: {$sum: {
        "$cond": [
                { $gte : ['$elements.startDate', new ISODate("2016-10-09T20:00:00Z")] },
                1,
                0
            ]
        }
    }}}
]);

The result should be 2, but this is not working, do you have any solution ?

Upvotes: 0

Views: 549

Answers (1)

Alex Blex
Alex Blex

Reputation: 37018

You need to unwind elements first.

db.collection.aggregate([
    {'$match': {userId: 1}},
    {$unwind: "$elements"},
    {$group: {_id: null, elements: {$sum: {
        "$cond": [
                { $gte : ['$elements.startDate', new ISODate("2016-10-09T20:00:00Z")] },
                1,
                0
            ]
        }
    }}}
]); 

As a side note, ensure your sum stuff does exactly what you expect when there are several documents in the elements array.

Upvotes: 2

Related Questions