I have a MongoDB collection with records in the following format:
[
{ "item1": { "a": 1 }, "item2": { "a": 2 } },
{ "item1": { "a": 3 }, "item3": { "a": 4 } },
{ "item1": { "a": 5 }, "item2": { "a": 6 } },
]
I want to get a count of records having the fields item1, item2, and item3 (They don't need to be dynamic. I have only a finite set of items). What I need is a count of records with field existing in the following fashion:
{ "item1": 3, "item2": 2, "item3": 1 }
For getting the count for item1, I do this:
db.collection.find({ "item1": { $exists: true }}).count()
Is there an easy way to aggregate the count of all three items in a single query?
You can use $objectToArray and $arrayToObject to count your keys dynamically:
db.collection.aggregate([
{
$project: { root: { $objectToArray: "$$ROOT" } }
},
{
$unwind: "$root"
},
{
$group: { _id: "$root.k", total: { $sum: 1 } }
},
{
$group: { _id: null, obj: { $push: { k: "$_id", v: "$total" } } }
},
{
$replaceRoot: { newRoot: { $arrayToObject: "$obj" } }
},
{
$project: { _id: 0 }
}
])
Mongo Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With