Document structure
{
"A": "1",
"B": "3",
"C": "0.000090213",
},
{
"A": "1",
"B": "3",
"C": "0.000037698",
},
{
"A": "2",
"B": "4",
"C": "0.00016664",
}
I'm trying to get the count of value for specific fields with aggregation, desired result for A and B would be
A: { "1": 2, "2": 1}
B: { "3": 2, "4": 1}
Any help is greatly appreciated.
db.collection.aggregate([
{
$facet: {
"A": [
{
$group: {
_id: "$A",
v: {
$sum: 1
}
}
}
],
"B": [
{
$group: {
_id: "$B",
v: {
$sum: 1
}
}
}
]
}
},
{
$addFields: {
A: {
$map: {
input: "$A",
as: "a",
in: {
k: "$$a._id",
v: "$$a.v"
}
}
}
}
},
{
$addFields: {
B: {
$map: {
input: "$B",
as: "b",
in: {
k: "$$b._id",
v: "$$b.v"
}
}
}
}
},
{
$project: {
A: {
"$arrayToObject": "$A"
},
B: {
"$arrayToObject": "$B"
}
}
}
])
Explained: