使用条件 MongoDB 计算嵌套元素



我有这个数据模型:

{_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}]}

我想计算具有startDate条件的用户的所有元素。

例如,计算userId:1startDate大于2016-10-09 20:00:00的元素数

我试过了

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

结果应该是2,但这不起作用,你有什么解决方案吗?

你需要

unwind elements

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
            ]
        }
    }}}
]); 

作为旁注,请确保您的sum内容在 elements 数组中有多个文档时完全符合您的预期。

最新更新