我有一堆文件,格式如下:
{
_id: "5b38c85f213751038ff4d0bb",
classes: [
{
_id: "5b38c85f21375103ytg65ju7",
standard: "12",
numberOfStudents: 45
},
{
_id: "5b38c85f2137510370987hgd",
standard: "11",
numberOfStudents: 51
},
]
}
我要
:_id
和特定类别的_id
搜索文档集合。numberOfStudents
。因此对于_id: "5b38c85f213751038ff4d0bb"
和classes._id: "5b38c85f21375103ytg65ju7"
,更新numberOfStudents: 43
我期望的结果是:
{
_id: "5b38c85f21375103ytg65ju7",
standard: "12",
numberOfStudents: 43
}
我尝试了几件事,但是它们都返回了整个文档,但没有返回我想要的样子。
答案 0 :(得分:1)
您可以尝试以下汇总
data
输出
db.collection.aggregate([
{ "$match": { "_id": "5b38c85f213751038ff4d0bb" }},
{ "$addFields": {
"classes": {
"$filter": {
"input": "$classes",
"as": "class",
"cond": {
"$eq": [
"$$class._id",
"5b38c85f21375103ytg65ju7"
]
}
}
}
}},
{ "$unwind": "$classes" },
{ "$replaceRoot": { "newRoot": "$classes" }},
{ "$project": {
"_id": 1,
"numberOfStudents": { "$literal": 43 },
"standard": 1
}}
])
尝试here