MongoDB搜索嵌套的对象数组

时间:2016-11-03 02:06:14

标签: mongodb mongodb-query mongodb-aggregation

这是我的数据。

{
    "applianceType": "light",
    "applianceId": "light123",
    "applianceName": "Light",
    "applianceImgURL": "https://s3-us-west-2.amazonaws.com/app.tiktok/appliance/icons/lights.svg",
    "inUsed": false,
    "collection": [{
        "category": "ceiling_light",
        "catgName": "Ceiling light",
        "catgImgURL": "https://s3-us-west-2.amazonaws.com/app.tiktok/appliance/catg_thumbs/light/ceiling_light.jpg",
        "collectionCatgId": "LI-ceil",
        "items": [{
            "id": "LI-CHL1234",
            "name": "Chandelier",
            "imgURL": "https://s3-us-west-2.amazonaws.com/app.tiktok/appliance/thumbs/light/chandelier.jpg",
            "capImgURL": "",
            "inUsed": false,
            "editable": true,
            "quantity": {
                "number": 1,
                "multiple": false
            },
            "value": {
                "state": "OFF",
                "range": {
                    "minVal": "0",
                    "currentVal": "20",
                    "maxVal": "100"
                }
            },
            "rooms": []
        }, {
            "id": "LI-PL1234",
            "name": "Pendant light",
            "imgURL": "https://s3-us-west-2.amazonaws.com/app.tiktok/appliance/thumbs/light/pendantlight.jpg",
            "capImgURL": "",
            "inUsed": false,
            "editable": true,
            "quantity": {
                "number": 1,
                "multiple": false
            },
            "value": {
                "state": "OFF",
                "range": {
                    "minVal": "0",
                    "currentVal": "20",
                    "maxVal": "100"
                }
            },
            "rooms": []
        }]
    }]
}

我想要的只是获取 collection.items

的特定文档

到目前为止,我已尝试过此查询:

db.myappliance.find(
    {
        "applianceType": "light"
    },
    {
        "collection" : {
            $elemMatch: {
                "category" : "ceiling_light",
                "items": {
                    $elemMatch: {
                        "id": "LI-CHL1234"
                    }
                }
            }
        }
    }
)

此查询为我提供了collection.items数组中的所有文档。但我只想要一个。我知道我的问题已经有很多重复的线程了。但我找不到任何适合我案例的答案。

1 个答案:

答案 0 :(得分:0)

query无法做到这一点。

从mongodb集合中获取查询结果后,使用它来检索所需对象。