使用条件MongoDB对嵌套元素进行计数

使用条件MongoDB对嵌套元素进行计数,mongodb,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,

我有这个数据模型:

{_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:1
startDate
大于
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,但这不起作用,您有什么解决方案吗?

您需要先执行
元素

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
            ]
        }
    }}}
]); 
作为旁注,当
元素
数组中有多个文档时,请确保您的
总和
内容完全符合您的预期

首先需要
元素

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
            ]
        }
    }}}
]); 
作为旁注,当
元素
数组中有多个文档时,请确保您的
总和
内容完全符合您的预期