Happy Coder
Happy Coder

Reputation: 4682

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 ??

Upvotes: 3

Views: 18158

Answers (2)

Niall Farrington
Niall Farrington

Reputation: 115

The aggregate operand needs to be inside the group {}

Upvotes: 0

Disposer
Disposer

Reputation: 6371

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 : ....,
     ...
   }
})

Upvotes: 11

Related Questions