我在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
}
]
答案 0 :(得分:2)
正如@Sajeetharan所说,到目前为止,azure cosmos db并不支持group by。但是,我建议您使用Stored Procedure
来实现您的要求。
根据您的示例文档,我为您提供了一个示例存储过程。请参考它。
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.');
}
输出:
希望它对你有所帮助。
答案 1 :(得分:0)
Cosmos DB本身不支持分组依据,因此没有开箱即用的方法来执行此查询。
然而,documentdb-lumenize允许您使用存储过程执行此操作。我自己没有用它,但值得研究。
链接是:
答案 2 :(得分:0)
现在可以在cosmosDB中进行分组依据 本文档包含所有详细信息 azure docs