宇宙相当于地图/选择

问题描述 投票:0回答:2

clients是我的doc中的一个数组,以下查询

SELECT 
f.id, f.clients
FROM f
where f.id ="35fb0733-dfa1-4932-9690-3ee5b05d89ff"

返回

[
    "id": "35fb0733-dfa1-4932-9690-3ee5b05d89ff",
    {
        "clients": [
            {
                "firstname": "Benjamin",
                "surname": "Bob",
            },
            {
                "firstname": "Rachael",
                "surname": "Smith",
            }
        ]
    }
]

但我希望客户看起来像:

"firstnames": [ "Benjamin", "Rachael" ]
"surnames": [ "Bob", "Smith" ]

这可能吗?

azure-cosmosdb azure-cosmosdb-sqlapi
2个回答
1
投票

您可以使用带有子查询的ARRAY表达式来实现这一点。

试试这个查询:

SELECT
    ARRAY(SELECT VALUE client.firstname FROM client IN f.clients) AS firstnames,
    ARRAY(SELECT VALUE client.surname FROM client IN f.clients) AS surnames
FROM f

0
投票

只需提供一个附加选项,您可以使用存储过程来获得所需的结果。

function sample() {
    var collection = getContext().getCollection();

    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT f.id, c.firstname,c.surname FROM f join c in f.clients where f.id ="1"',
    function (err, feed, options) {
        if (err) throw err;
        var map = {};
        var firstname = [];
        var surname =[];
        if (!feed || !feed.length) {
            var response = getContext().getResponse();
            response.setBody('no docs found');
        }
        else {
            for(var i=0;i<feed.length;i++){              
                map["id"] = feed[i].id;
                firstname.push(feed[i].firstname);
                surname.push(feed[i].surname);
            }
            map["firstname"] = firstname;
            map["surname"] =surname;

            var response = getContext().getResponse();
            response.setBody(map);
        }
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

测试输出:

{
    "id": "1",
    "firstname": [
        "Benjamin",
        "Rachael"
    ],
    "surname": [
        "Bob",
        "Smith"
    ]
}

希望它能帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.