我在mongodb中有一个文档,其模式如下:
{ japanese3:
{ '0':
{"japanese3a": 100, "japanese3b": 100, "japanese3c": 100}
}
}我想得到japanese3a,japanese3b和japanese3c的值之和,也就是300。
这是我试图得到的总和,但每次我尝试,控制台显示什么都没有。
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);
})
}
}); 编辑:我在显示脚本和文档布局时出错。
发布于 2021-02-16 12:05:09
待处理的文件如下。它是嵌套对象:一个对象(值为100的键值对)嵌套在一个对象('0')中(这是一个字符串),而这个对象嵌套在另一个对象("japanese3")中。用户名用作查询以获得正确的文档。
{ japanese3:
{ '0':
{"japanese3a": 100, "japanese3b": 100, "japanese3c": 100}
}
}目的是对嵌套最深入的对象中的数值进行求和,因此所期望的结果是"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
});
});https://stackoverflow.com/questions/66194193
复制相似问题