gpt4 book ai didi

azure - 如何计算cosmos DB中的不同值

转载 作者:行者123 更新时间:2023-12-02 23:45:35 25 4
gpt4 key购买 nike

我在 Cosmos DB 中创建了一些文档,如下所示:

[
{
"class": "class01",
"student": {
"lastReport": [
{
"Name": "st01",
"score": "C"
},
{
"Name": "st02",
"score": "B"
}
],
"lastTime": "2018-05-10"
}
},
{
"class": "class02",
"student": {
"lastReport": [
{
"Name": "st03",
"score": "C"
},
{
"Name": "st01",
"score": "A"
}
],
"lastTime": "2018-05-10"
}
},
{
"class": "class01",
"student": {
"lastReport": [
{
"Name": "st01",
"score": "C"
},
{
"Name": "st02",
"score": "A"
},
{
"Name": "st03",
"score": "B"
}
],
"lastTime": "2018-05-10"
}
}
]

你能帮我计算所有数据中的分数值吗?我的期望是这样的结果:

[
{
"score": "C",
"Num" : 3
},
{
"score": "B",
"Num" : 2
},
{
"score": "A",
"Num" : 2
}
]

最佳答案

正如@Sajeetharan所说,到目前为止,azure cosmos db不支持group by。但是,我建议您使用存储过程来实现您的要求。

根据您的示例文档,我为您提供了一个示例存储过程。请引用一下。

function sample() {
var collection = getContext().getCollection();
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT a.score FROM c join a in c.student.lastReport',
function (err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) getContext().getResponse().setBody('no docs found');
else {
var map = {};
var returnResult = [];
for(var i = 0;i<feed.length;i++){
var s = feed[i].score;
if(map.hasOwnProperty(s)){
map[s] ++;
}else {
map[s] = 1;
}
}

for(var key in map){
console.log(key)
var obj = {
"score":key,
"num" : map[key]
};
returnResult.push(obj);
}
getContext().getResponse().setBody(returnResult);
}
});

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

输出:

enter image description here

希望对您有帮助。

关于azure - 如何计算cosmos DB中的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50637169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com