我正在尝试查找对象中值的平均值。这些值保存在mongodb中,但保存为字符串。我想找到平均值并返回表格。
文档:
{
{
"_id": "someId",
"english": "78",
"literature": "78",
"period": "1st Period"
}{
"_id": "someId",
"english": "90",
"literature": "90",
"period": "2nd Period"
}{
"_id": "someId",
"english": "70",
"literature": "99",
"period": "3rd Period"
}{
"_id": "someId",
"english": "50",
"literature": "60",
"period": "First Sem. Exam"
}{
"_id": "someId",
"english": "68",
"literature": "88",
"period": "4th Period"
}{
"_id": "someId",
"Average": "",
"period": "First Sem. Average"
}{
"_id": "someId",
"english": "40",
"literature": "77",
"period": "5th Period"
}{
"_id": "someId",
"english": "70",
"literature": "66",
"period": "6th Period"
}{
"_id": "someId",
"english": "55",
"literature": "79",
"period": "Second Sem. Exam"
}{
"_id": "someId",
"Average": "",
"period": "Second Sem. Average"
}
}
如文档中所述,我想获取1st Period, 2nd Period, 3rd Period
和First Sem. Exam
的平均值并将其返回到表中
有没有办法实现这一目标?
答案 0 :(得分:0)
请记住,docs
是一个数组,这应该给您一个很好的主意,如何获得英语平均水平。首先,从数组中提取所需的四个周期。然后,您提取所需的结果。最后,您只需要进行平均即可。
const filteredDocs = docs.filter(element => {
return (
element.period === "1st Period" ||
element.period === "2nd Period" ||
element.period === "3rd Period" ||
element.period === "First Sem. Exam"
);
});
const englishResults = filteredDocs.map(element => {
return parseInt(element.english);
});
const englishAverage =
englishResults.reduce((a, b) => a + b, 0) / englishResults.length;