Mongo:我如何从数组中获取元素

时间:2017-01-21 17:38:49

标签: mongodb mongodb-query

我是Mongo的新手。我有一个这样的json结构

{
    "_id": ObjectId(
        "aaaaaaa"
    ),
    "university": {
        "short_name": "...",
        "full_name": "...",
        "faculties": [{
            "id": 287,
            "short_name": "...",
            "full_name": "...",
            "departments": [{
                "id": 337,
                "short_name": "...",
                "full_name": "...",
                "teachers": [{
                    "id": 1053,
                    "short_name": "X1",
                    "full_name": "Y1"
                }, {
                    "id": 549,
                    "short_name": "X2",
                    "full_name": "Y2"
                }]
            }]
        }]
    }
}

我想通过university.faculties.departments.teachersID获取教师元素(short_name),但不幸的是检索或没有或整个文档。我尝试使用$elemMatch,但它不适用于嵌套对象。

2 个答案:

答案 0 :(得分:1)

您需要使用projection

db.school.find(
    {
        _id : "document_id", 
        "university.short_name" : "..."
    }, 
    {
        "university.faculties.departments.teachers" : 1
        , _id : 0
    }
)

答案 1 :(得分:1)

如果您只需要获取teacher对象,则可以使用如下聚合:

db.test.aggregate([{
        // match teacher id to exclude irrelevant documents
        "$match": {
            "university.faculties.departments.teachers.id": 1053
        }
    },
    {
        // unwind faculties array
        $unwind: "$university.faculties"
    }, {
        // unwind departments array
        $unwind: "$university.faculties.departments"
    }, {
        // filter teacher id
        $project: {
            teachers: {
                $filter: {
                    input: "$university.faculties.departments.teachers",
                    as: "teachers",
                    cond: { $eq: ["$$teachers.id", 1053] }
                }
            }
        }
    }, {
        // unwind teachers array (created with $filter)
        $unwind: "$teachers"
    }, {
        // group by teachers field
        $group: {
            _id: "$teachers"
        }
    }
])

给出:

{ "_id" : { "id" : 1053, "short_name" : "X1", "full_name" : "Y1" } }