gets the total matching number of documents using mongo aggregate

859 Views Asked by At

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.

1

There are 1 best solutions below

2
On

Got your question correctly now

Please see this updated query it will give us the desired result

db.result.aggregate([
{$group:{'_id':{name:'$name', id:'$id', date:'$date', amount:'$amount'}, 
totalAmount:{$sum:'$amount'},
count:{'$sum':1}}},
{$match:{'count':{'$gt':1}}},
{$sort:{'count':-1}}])

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

{
        "_id" : {
                "name" : "vendor2",
                "id" : "2",
                "date" : ISODate("2017-04-29T00:00:00Z"),
                "amount" : 380
        },
        "totalAmount" : 760,
        "count" : 2
}
{
        "_id" : {
                "name" : "vendor3",
                "id" : "3",
                "date" : ISODate("2017-04-29T00:00:00Z"),
                "amount" : 702
        },
        "totalAmount" : 1404,
        "count" : 2
}

Hope it Helps!