如何对MongoDB集合中字段的不同值求和(使用猫鼬) [英] How to sum distinct values of a field in a MongoDB collection (utilizing mongoose)
问题描述
想象一下,我有一个名为 journals 的集合,其中包含如下文件:
Imagine I had a collection called journals containing documents like the following:
{
"article": "id1",
"d": 2
},
{
"article": "id1",
"d": 2
},
{
"article": "id1",
"d": 3
},
{
"article": "id2",
"d": 2
},
...
其中 d 是一种开关,而 article 是参考.现在我想得到如下结果:
Where d is kind of a switch and article is a reference. Now I want to have a result like the following:
[
{
"_id": "id1",
"total": 3,
"d2": 2,
"d3": 1
},
{
"_id": "id2",
"total": 1,
"d2": 1,
"d3": 0
}
]
我正在使用猫鼬,并且有一个名为 Journal 的模型.到目前为止,我得到的是……
I'm using mongoose and have a model called Journal. What I've got so far is…
Journal.aggregate(
{ $project: {
articleId: 1,
depth2 : { $gte:['$d', 2] },
depth3 : { $eq:['$d', 3] }
}},
{ $group: {
_id: '$article',
total: { $sum: 1 },
d2: { $sum: '$depth2'},
d3: { $sum: '$depth3'}
}
},
function (err, journal) {
console.log(journal);
}
);
其结果是:
[
{
"_id": "id1",
"total": 3,
"d2": 0,
"d3": 0
},
{
"_id": "id2",
"total": 1,
"d2": 0,
"d3": 0
}
]
很显然,这里的错误是$eq:['$d', 3]
不被求和,因为这会导致布尔值.
Obviously the error here is that $eq:['$d', 3]
is not summed up because that results in a boolean.
那么,有没有更好的表达式可以将新的depth2和depth3字段投影到1
或0
而不是true
或false
?
还是有一个完整且更好的方法? :)
So is there a better expression that projects the new depth2 and depth3 fields to 1
or 0
instead of true
or false
?
Or is there a complete and better approach? :)
我想避免进行3个查询并在匹配阶段之前添加{ $match: { d: 2 } }
.
I'd like to avoid making 3 queries and prepending a matching phase like { $match: { d: 2 } }
.
推荐答案
您可以使用 $cond
将布尔值转换为数值,但是您还得到了$gte
,其中似乎是$eq
应该是,而您的文档使用article
代码使用articleId
:
You can use $cond
to convert a boolean to a numerical value, but you've also got a $gte
where it seems an $eq
should be and your docs use article
while your code uses articleId
:
Journal.aggregate([
{ $project: {
article: 1,
depth2 : { $cond: [{$eq: ['$d', 2]}, 1, 0] },
depth3 : { $cond: [{$eq: ['$d', 3]}, 1, 0] }
}},
{ $group: {
_id: '$article',
total: { $sum: 1 },
d2: { $sum: '$depth2'},
d3: { $sum: '$depth3'}
}
}
]);
输出:
{
"result" : [
{
"_id" : "id2",
"total" : 1,
"d2" : 1,
"d3" : 0
},
{
"_id" : "id1",
"total" : 3,
"d2" : 2,
"d3" : 1
}
],
"ok" : 1
}
这篇关于如何对MongoDB集合中字段的不同值求和(使用猫鼬)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!