我正在收集数组an_array
和字段a_field
。数组可以是由数值组成(数组可能为空),它也可以存在于a_field
中。MongoDB集合中的字段和数组的总和
我想要创建一个汇总函数,它将a_field
或an_array
中的值的数量相加。
编辑:例如我想要计算在a_field
和an_array
等中使用1
多少次。
例如,如果我有一些文件,看起来像这样:
{
a_field: 1,
an_array: [ 1, 3, 4 ],
},
{
a_field: 3,
an_array: [],
}
{
a_field: 2,
an_array: [ 1 ],
}
我想看到像这样的输出:
[ { _id: 1, a_count: 1, b_count: 2 }, { _id: 2, a_count: 1, b_count: 0 }, { _id: 3, a_count: 1, b_count: 1 }, { _id: 4, a_count: 0, b_count: 1 } ]
但是我得到的输出是这样的:
[ { _id: 1, a_count: 1, b_count: 2 }, { _id: 3, a_count: 1, b_count: 1 }, { _id:4, a_count: 1, b_count: 1 } ]
这是不正确的,因为它缺少_id
2,和_id
4有太多的数字。
然而,我面临的问题是,当an_array
为空时,如果数组为空,我将无法正确检索所有计数,并且它会得到a_count
的值,该值不总是与实际的id匹配(如可在_id
4中看到的)。
我到目前为止是这样的:
db.getCollection('test').aggregate([
{ $match: {
a_field: {
$ne: null
}
} },
{ $group: {
_id: '$a_field',
a_count: {
$sum: 1
},
an_array: {
$push: {
an_array: '$an_array'
}
}
} },
{ $project: {
an_array: 1,
a_count: 1
} },
{ $unwind: '$an_array' },
{ $unwind: '$an_array.an_array' },
{ $group: {
_id: '$an_array.an_array',
b_count: {
$sum: 1
},
a_count: {
$first: '$a_count'
}
} },
]);
我真的很感激一些投入,因为我喜欢做在一个单一的聚合。在这一点上,这已经变成了比实际实施更个人化的任务。谢谢!
编辑:我现在绑定到MongoDB 2.6。
为什么使用需要应用'$ sum'为'a_field'如果不是一个数组?在预期的输出中是什么'_id'? – styvane
输出中的_id是当前的'an_array'值之一。这也是我所期望的,我得到一个数字的清单,并有一笔数额。你是什么意思为什么我们需要申请'$ sum'?如果我想继续指望它被添加的次数,那是唯一的方法,不是吗? –
其实,你已经向我们展示了3个文档,并且在你的预期输出中你有4个。另外,如果你想要的是'an_array'字段中的不同项目,而不等于'a_field',那么你做错了。即使不明显,也有更好的方法来做到这一点。你应该考虑改善你的问题。 – styvane