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