我正在尝试匹配文档数组中的某些值。但我没有运气这么做。 这是文件:
{
"student": "Pedro",
"class_id": 10,
"scores": [
{
"type":"exam",
"score": 10
},
{
"type":"homework",
"score": 10
}
]
}
我想匹配得分。分数在哪里考试,我试过这个
db.class.aggregate(
{
$unwind: "$scores"
},
{
$group: {
_id: "$class_id"
}
},
{
$match:{
"$scores.score": "exam"
}
}
)
但它不起作用,有什么建议吗?
答案 0 :(得分:1)
我假设您要对class_id
进行分组,并将得分类型为exam
的所有得分相加。这是一个简单的聚合查询
db.collection.aggregate([
{
$unwind:"$scores"
},
{
$match:{
"scores.type":'exam'
}
},
{
$group:{
_id:"$class_id",
sumOfScores:{
$sum:"$scores.score"
}
}
}
])
输出:
{ "_id" : 10, "sumOfScores" : 10 }