I've used Mongodb aggregation, $facet as I wanted to count every value of "reli" and "prov" from the collection.
This is my code to get results from db.
const keyy = await db.aggregate([
$facet: { "reli": [
{ $group: { _id: '$reli', count: { $sum: 1 } } } ],
"prov": [
{ $group: { _id: '$prov', count: { $sum: 1 } } }
],
])
Output Looks like this:
[
{
"reli": [
{
"_id": "abcdef",
"count": 6
},
{
"_id": "ghij",
"count": 1
},
],
"prov": [
{
"_id": "hello",
"count": 63
},
{
"_id": "hey",
"count": 9
},
]
}
]
But I want That my Expected output is :
[
{
"reli":[
{abcdef: 6},
{ghij: 1}
],
"prov":[
{"hello": 63},
{"hey": 9}
]
}
]
You can iterate using $map and generate the new array with the values you want using $arrayToObject like this:
This query simply overwrite values reli and prov with the result of the map. That result is an array compound by objects where the key k is the _id value and the value v is the count value.
db.collection.aggregate([
{
"$project": {
"reli": {
"$map": {
"input": "$reli",
"in": {
"$arrayToObject": [
[
{
k: "$$this._id",
v: "$$this.count"
}
]
]
}
}
},
"prov": {
"$map": {
"input": "$prov",
"in": {
"$arrayToObject": [
[
{
k: "$$this._id",
v: "$$this.count"
}
]
]
}
}
}
}
}
])
Example here