我有MongoDb数据如下
{
"_id" : 7,
"name" : "Salena Olmos",
"scores" : [
{
"type" : "exam",
"score" : 90.37826509157176
},
{
"type" : "quiz",
"score" : 42.48780666956811
},
{
"type" : "homework",
"score" : 67.18328596625217
},
{
"type" : "homework",
"score" : 96.52986171633331
}
]
}
我想把“类型”的“分数”加起来:“作业”
{ "_id" : 7, "score" : 163.71314768258548}
我使用聚合和过滤条件编写了我的查询,如下所示
db.students.aggregate([
{
"$group" :
{
"_id":"$_id",
"score":{$sum: {$filter: {
input: "$scores",
as: "x",
cond: {$eq : ["$$x.type", "homework"]}
}
}
}
}
}
])
但是所有它给我的总和值为“0”:
{ "_id" : 7, "score" : 0 }
请帮助我,我是MongoDb的新手,并试图通过解决一些运动问题来学习。
谢谢
您可以使用以下聚合。使用$let
从匹配分数中提取分数。
db.students.aggregate({
"$project":{
"score":{
"$sum":{
"$let":{
"vars":{
"mscores":{
"$filter":{
"input":"$scores",
"as":"x",
"cond":{"$eq":["$$x.type","homework"]}
}
}
},
"in":"$$mscores.score"
}
}
}
}
})
我已经浏览了MongoDb文档并提出了以下解决方案
db.students.aggregate([
{$unwind: "$scores"},
{$match:{"scores.type" : "homework"}},
{$group : {"_id":"$_id", "score":{$sum: "$scores.score"}}}
])