/* 1 */
{
"_id" : ObjectId("5a98b0574fc9b46a80b5e250"),
"a" : "1"
}
/* 2 */
{
"_id" : ObjectId("5a98b05a4fc9b46a80b5e251"),
"a" : "2"
}
/* 3 */
{
"_id" : ObjectId("5a98b0614fc9b46a80b5e252"),
"b" : "1"
}
/* 4 */
{
"_id" : ObjectId("5a98b0654fc9b46a80b5e253"),
"c" : "1"
}
/* 5 */
{
"_id" : ObjectId("5a98b0684fc9b46a80b5e254"),
"d" : "1"
}
/* 6 */
{
"_id" : ObjectId("5a98b06c4fc9b46a80b5e255"),
"e" : "1"
}
/* 7 */
{
"_id" : ObjectId("5a98b0714fc9b46a80b5e256"),
"e" : "2"
}
/* 8 */
{
"_id" : ObjectId("5a98b0754fc9b46a80b5e257"),
"c" : "2"
}计算如上数据每个字段的和,要求结果为:a=3,b=1,c=3,d=1,e=3
var a_count=0;
var b_count=0;
var c_count=0;
var d_count=0;
var e_count=0;
db.movies.find({
})
.forEach(
function(myDoc) {
if (typeof(myDoc.a) != "undefined") {
a_count = a_count+parseInt(myDoc.a);
}
if (typeof(myDoc.b) != "undefined") {
b_count = b_count+parseInt(myDoc.b);
}
if (typeof(myDoc.c) != "undefined") {
c_count = c_count+parseInt(myDoc.c);
}
if (typeof(myDoc.d) != "undefined") {
d_count = d_count+parseInt(myDoc.d);
}
if (typeof(myDoc.e) != "undefined") {
e_count = e_count+parseInt(myDoc.e);
}
}
)
print("a_count="+a_count)
print("b_count="+b_count)
print("c_count="+c_count)
print("d_count="+d_count)
print("e_count="+e_count)结果如下:
本文介绍了一种使用MongoDB聚合框架来计算数据库中特定字段总和的方法。通过遍历集合并检查每个文档的字段是否存在及是否为数值类型,最终计算出各字段的总和。这种方法适用于动态模式的数据集。
1万+





