相当于地图的宇宙/选择

时间:2018-09-18 18:21:49

标签: azure-cosmosdb azure-cosmosdb-sqlapi

intent是我的文档中的一个数组,以下查询

clients

返回

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",
            }
        ]
    }
]

这可能吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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"
    ]
}

希望它对您有帮助。