Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo DB aggregate not working

I have the following data in a mongo collection (datacollection) :

{
  "_id": ObjectId("54980efef7db7d9b018d375b"),
  "sub_id": "1234567890",
  "points": "10",
  "oid": "1",
  "name": "test",
  "app": "e53abc6d12fea63c80e4c2e1d49e",
  "source": "mysource",
  "product_name": "browser",
  "added": ISODate("2014-12-22T12:30:54.618Z"),
  "added_human": "2014-12-22 06:30:54",
  "checked": true
}

I actually need to find out the sum of points grouped by date. The SQL query will look like : SELECT DATE(added) as point_date, SUM(points) AS total_points FROM mytable WHERE added between 'from' AND 'to' GROUP BY DATE(added).

So I am using the following aggregation :

db.datacollection.aggregate(
    { 
        $match:{
            "added" : {$gte:ISODate("2014-12-01"), $lt:ISODate("2014-12-25")},   
            "source":"mysource"  
        },   
        $group : {
            "_id" : { month: { $month: "$added" }, day: { $dayOfMonth: "$added" }, year: { $year: "$added" } },
            "total_points":{$sum:"$points"}   
        }  
    }  
);

But this is showing

"errmsg" : "exception: A pipeline stage specification object must contain exactly one field.",

How this can be fixed or is there any better method for doing this calculation ??

like image 775
Happy Coder Avatar asked Jan 26 '26 17:01

Happy Coder


1 Answers

use this:

db.datacollection.aggregate(
    { 
        $match:{
            "added" : {$gte:ISODate("2014-12-01"), $lt:ISODate("2014-12-25")},   
            "source":"mysource"  
        }
    },   
    {   $group : {
            "_id" : { month: { $month: "$added" }, day: { $dayOfMonth: "$added" }, year: { $year: "$added" } },
            "total_points":{$sum:"$points"}   
        }  
    }  
);

You should use this format (every pipeline in in {} pair)

db.collection.aggrgation ( 
   { $group: ....},
   { $match : .... },
   ...
})

but you used:

db.collection.aggrgation ( 
   { $group: ....,
     $match : ....,
     ...
   }
})
like image 66
2 revs, 2 users 67% Avatar answered Jan 28 '26 19:01

2 revs, 2 users 67%