Azure Cosmos DB mongo db api: attribute wise count for the records

Alpee Jain 96 Reputation points
2020-07-21T11:03:53.613+00:00

Hi,

I have my data stored in azure cosmos db (Mongo db API), sample of the data is as shown below:
currently, i query based on the apptype, my requirement is to show the count of each attribute as well. eg: in the example below, there are two records with "ct" as 4000 and 1 record of 7000. I have to show the count against all the attributes in my document.
Would need help in how can we achieve this without compromising with the performance?

{
"_id" : ObjectId("5ad88af611f6f87cba45c8a5"),
"name" : "C-PHB-A",
"apptype":"AreaLight",
"ct" : [
4000,
5000
],
"voltages" : [
"120-277"
],
"types" : [
"Linear"
]
},

{
"_id" : ObjectId("5ad88af611f6f87cba45c8a5"),

"name" : "12-PHB-A",   
"apptype":"AreaLight",  
"ct" : [  
	4000,  
	5000,  
	7000  
],  
"voltages" : [  
	"120-277"  
],  
"types" : [  
	"Linear"  
]  

}

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,632 questions
{count} votes

Accepted answer
  1. Alpee Jain 96 Reputation points
    2020-07-28T10:17:36.917+00:00

    Finally, I was able to sort out. Mongo db has support for $facet attribute which allows you to do aggregation in multiple stages:
    db.getCollection("testfixturefamilies").aggregate(
    [
    {
    "$match" : {
    "applicationType" : "Highbay"
    }
    },
    {
    "$facet" : {
    "types" : [
    {
    "$unwind" : "$colorTempeartures"
    },
    {
    "$group" : {
    "_id" : "$colorTempeartures",
    "name" : {
    "$first" : "$colorTempeartures"
    },
    "count" : {
    "$sum" : 1.0
    }
    }
    }
    ],
    "voltages" : [
    {
    "$unwind" : "$voltages"
    },
    {
    "$group" : {
    "_id" : "$voltages",
    "name" : {
    "$first" : "$voltages"
    },
    "count" : {
    "$sum" : 1.0
    }
    }
    }]

    );

    Advantage of using facets is that the data is just obtained once and is passed to the different stages, This is the output you will get:
    {
    "colorTemperatures" : [
    {
    "_id" : "4000",
    "name" : "4000",
    "count" : 1.0
    }
    ],
    "voltages" : [
    {
    "_id" : "120-277",
    "name" : "120-277V",
    "count" : 2.0
    }
    ]
    }


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.