Reputation: 63
I created some documents in Cosmos DB like this:
[
{
"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"
}
}
]
Could you help me how to count value of score in all data? My expectation is the result like this:
[
{
"score": "C",
"Num" : 3
},
{
"score": "B",
"Num" : 2
},
{
"score": "A",
"Num" : 2
}
]
Upvotes: 2
Views: 2650
Reputation: 877
Group by is possible in cosmosDB now This document contains all the details azure docs
Upvotes: 0
Reputation: 23782
As @Sajeetharan said, group by is not supported by azure cosmos db so far. However , I suggest you using Stored Procedure
to implement your requirement.
Base on your sample documents, I provide you with a sample stored procedure. Please refer to it.
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.');
}
Output :
Hope it helps you.
Upvotes: 2
Reputation: 106
Group by isn't supported natively in Cosmos DB so there is no out of the box way to execute this query.
There is however documentdb-lumenize that allows you to do this using stored procedures. I haven't used it myself but it may be worth looking into.
Link is:
https://github.com/lmaccherone/documentdb-lumenize
Upvotes: 0