[英]How to add elements of an array of field in mongodb?
I have a collection in the following format: 我有以下格式的集合:
{
"_id" : ObjectId("5877540712b0de70db15f3e2"),
"student_name" : "neel",
"roll_no" : 1,
"marks" : [
{
"subject1" : 44,
"subject2" : 99,
"subject3" : 67,
"subject4" : 43
}
]
}
I need to create a JavaScript function with parameter roll_no
to find the percentage of a student. 我需要使用参数
roll_no
创建一个JavaScript函数来查找学生的百分比。
Note : $add
doesn't work with arrays. 注意:
$add
不适用于数组。
My functions is: 我的职能是:
function findpercentage(no) {
db.marks1.aggregate({
$match: {
"roll_no": no
}
}, {
$project: {
"student_name": 1,
"total": {
$divide: [$add: ["$marks.subject1", "$marks.subject2", "$marks.subject3", "$marks.subject4"], 4]
}
});
}
finally i got a solution , though $unwind isn't working. 终于我有了一个解决方案,尽管$ unwind无法正常工作。
function findpercentage1(no) {
db.marks1.aggregate([
{ $match:{roll_no:no}},
{ $project: {
"student_name": 1,
percentage: {
$divide:[
{$add: [ { $arrayElemAt: [ "$marks", 0 ] },
{ $arrayElemAt: [ "$marks", 1 ] },
{ $arrayElemAt: [ "$marks", 2 ] },
{ $arrayElemAt: [ "$marks", 3 ] }
] },
4
]
}
}
}
]).forEach(function(pnt)
{
print(pnt.percentage);
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.