I am trying to get the total number of matching documents on a set of fields using mongo aggregate. The aggregation query is like,
db.results.aggregate([
{$group:{'_id':{name:'$name', id:'$id', date:'$date', amount:'$amount'},
count:{'$sum':1}}},
{$match:{'count':{'$gt':1}}},
{$sort:{'count':-1}}])
so how to sum the count
of all the matching documents here?
a set of sample docs are like,
{
"id" : "1",
"date" : ISODate("2017-04-29T00:00:00.000Z"),
"amount" : 697,
"name" : "vendor1"
}
{
"id" : "2",
"date" : ISODate("2017-04-29T00:00:00.000Z"),
"amount" : 380
"name" : "vendor2"
}
{
"id" : "2",
"date" : ISODate("2017-04-29T00:00:00.000Z"),
"amount" : 380,
"name" : "vendor2"
}
{
"id" : "3",
"date" : ISODate("2017-04-29T00:00:00.000Z"),
"amount" : 702,
"name" : "vendor3"
}
{
"id" : "3",
"date" : ISODate("2017-04-29T00:00:00.000Z"),
"amount" : 702,
"name" : "vendor3"
}
UPDATE
came across toArray()
, so the solution seems to be,
db.results.aggregate([
{$group:{'_id':{name:'$name', id:'$id', date:'$date', amount:'$amount'},
count:{'$sum':1}}},
{$match:{'count':{'$gt':1}}},
{$sort:{'count':-1}}],
{allowDiskUse:true}).toArray().length
no, it only gives me the number of matching clusters.
Got your question correctly now
Please see this updated query it will give us the desired result
The sum of all counts is given in the totalAmount field
The result of the aggregation query given above based on the sample collection data you have provided is
Hope it Helps!