MongoDB:$nest文档中的匹配查询
我正在尝试匹配文档数组中的一些值。但我运气不好。 文件如下:MongoDB:$nest文档中的匹配查询,mongodb,Mongodb,我正在尝试匹配文档数组中的一些值。但我运气不好。 文件如下: { "student": "Pedro", "class_id": 10, "scores": [ { "type":"exam", "score": 10 }, { "type":
{
"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"
}
}
)
但它不起作用,有什么建议吗 我假设您想要分组
class\u id
并对所有分数类型为exam
的分数进行求和。下面是一个简单的聚合查询
db.collection.aggregate([
{
$unwind:"$scores"
},
{
$match:{
"scores.type":'exam'
}
},
{
$group:{
_id:"$class_id",
sumOfScores:{
$sum:"$scores.score"
}
}
}
])
输出:
{ "_id" : 10, "sumOfScores" : 10 }
@丹尼,我希望这能解决你的问题