首页 > 解决方案 > 过滤嵌套数组项 CosmosDb

问题描述

是否可以在 CosmosDb 中过滤数组项?例如,我只需要客户信息和第一只宠物(在数组中)

当前结果:

[
{
    "CustomerId": "100",
    "name": "John",
    "lastName": "Doe",
    "pets": [
        {
            "id": "pet01",
            "CustomerId": "100",
            "name": "1st pet"
        },
        {
            "id": "pet02",
            "CustomerId": "100",
            "name": "2nd pet"
        }
    ]
}
]

预期的:

[
{
    "CustomerId": "100",
    "name": "John",
    "lastName": "Doe",
    "pets": [
        {
            "id": "pet01",
            "CustomerId": "100",
            "name": "1st pet"
        }
    ]
}
]

标签: nosqlazure-cosmosdbazure-cosmosdb-sqlapi

解决方案


您可以使用ARRAY_SLICE函数。

SQL:

SELECT c.CustomerId,c.name,c.lastName,ARRAY_SLICE(c.pets,0,1) as pets 
FROM c

结果:

[
    {
        "CustomerId": "100",
        "name": "John",
        "lastName": "Doe",
        "pets": [
            {
                "id": "pet01",
                "CustomerId": "100",
                "name": "1st pet"
            }
        ]
    }
]

推荐阅读