Mongodb从数组中的数组-嵌套数组

时间:2019-10-23 13:39:09

标签: mongodb mongodb-query

下面是我的environment数据结构

"environments" : [
        {
            "environmentId" : "375daa2e-d7e1-42ef-b40a-83e50f1ffa32",
            "environmentName" : "Urban",
            "environmentType" : "green",
            "services" : [
                {
                    "serviceId" : "78a2ec19-6b71-447b-9f0d-8978204274af",
                    "serviceName" : "railways",
                    "serviceType" : "transport"
                },
                {
                    "serviceId" : "5dddddddd-6b71-447b-9f0d-8978204274af",
                    "serviceName" : "Doctor",
                    "serviceType" : "people"
                },
                {
                    "serviceId" : "4ddddddd-6b71-447b-9f0d-8978204274af",
                    "serviceName" : "Bus",
                    "serviceType" : "transport"
                }

            ]
        }
    ]

我正在使用serviceId进行查询,并尝试仅获取匹配的service元素

db.mydatabase.find( {'environments.services' : { $elemMatch: { 'serviceId': "78a2ec19-6b71-447b-9f0d-8978204274af" }}},{'environments.services.$': 1} ).pretty()

但是它返回了services中的所有environment ..但我只想要匹配的service

2 个答案:

答案 0 :(得分:0)

尝试此查询

diet_projection = perc_contributions_WRAP.percentage_contributions(diet_props, 2050, 1961, 2013)

答案 1 :(得分:0)

我能够通过$unwind操作来做到这一点

db.myDatabase.aggregate({$unwind:'$environments'}, {$unwind:'$environments.services'}, {$match:{ 'environments.services.serviceId':"e8a3192f-ab2f-4b9a-b7ab-5d7c5c68153e"}},{$project: {'services':'$environments.services'}}).pretty();