您如何使用node.js对mongodb中嵌套子文档的对象中的值求和? [英] How do you sum the values within an object which is a nested subdocument in mongodb using node.js?
问题描述
我在mongodb中有一个文档,其架构如下:
I have a document in mongodb whose schema is like this:
{ japanese3:
{ '0':
{"japanese3a": 100, "japanese3b": 100, "japanese3c": 100}
}
}
我想获取japanese3a,japanese3b和japanese3c的值之和,即300.
I want to get the sum of the values of japanese3a, japanese3b and japanese3c, which is 300.
这是我尝试获取的总和,但是每次尝试时,控制台都不会显示任何内容.
This is what I have tried to get the sum but everytime I try it, the console shows nothing.
var docs = await db.collection("myCollection")
.aggregate([
{$project: {_id:1, username:1, group:1, japanese3:1}},
{$match: {username: username}},
{$unwind: "$japanese3"},
{$addFields:
{total:
{$sum:
{$map:
{input:
{$objectToArray:"$japanese3"}, as: "kv", in: "$$kv.v"
}
}
}
}
}
])
.toArray(function(err, result){
if (err) console.log("Didn't work");
console.log(result);
res.end(result);
})
}
});
我在显示脚本和文档布局时出错.
EDITED: I made an error in displaying the script and the document layout.
推荐答案
要处理的文档如下.它是嵌套的对象:一个对象(值为100的键-值对)嵌套在一个对象('0')(写为字符串)中,并且嵌套在另一个对象("japanese3")中.用户名用作获取正确文档的查询.
The document to be worked on is below. It is nested objects: an object (key-value pairs with the value being 100) is nested within an object ('0') (this is written as a string), and this is nested inside another object ("japanese3"). The username is used as a query to get the right document.
{ japanese3:
{ '0':
{"japanese3a": 100, "japanese3b": 100, "japanese3c": 100}
}
}
目标是对最深嵌套的对象中的数字值求和,因此所需结果为"300".
Aim is to sum the number values in the most deeply nested object, so the desired result is "300".
脚本为:
.aggregate([
{$match: {username: username}}, //finds the document by username
{$set: {"japanese_array":{$objectToArray: "$japanese3.0"}}}, // all fields have the same name now (k, v)
{$project: {_id:0, total:{$sum: "$japanese_array2.v"}}}// sum up the "v" fields
])
.toArray(function(err, result){
if (err)
console.log("Failed");
console.log(result);
res.send({ status: true, msg: result[0].total}); //result shows up as a number, in this case: 300
});
});
这篇关于您如何使用node.js对mongodb中嵌套子文档的对象中的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!