How to do I Aggregate group by Year/Month/Day using the C# driver.

1,221 views
Skip to first unread message

Colin G

unread,
May 18, 2017, 10:07:42 AM5/18/17
to mongodb-user
I am trying to get a count of documents in my collection by year/month/day. 

I have been able to piece together the following query but it does not want to return any results. 


   var aggregate = this.collection.Aggregate()
                .Match(filterDefinition)
               .Group(new BsonDocument { { "_id",
                   new BsonDocument {
                       { "month", new BsonDocument("$month", "$timestamp") },
                   { "day", new BsonDocument("$dayOfMonth", "$timestamp") },
                   { "year", new BsonDocument("$year", "$timestamp") } } },
                   { "count", new BsonDocument("$sum", 1) } });
         
            IAsyncCursor<BsonDocument> asyncCursor = aggregate.ToCursor();
            var x = asyncCursor.ToList();



when I run this query in RoboMongo it throws an exception

db.getCollection('MyCollection).aggregate([
{ "$match" : { "filter_key" : "uniquefilterKey-123456", "@timestamp" : 
    { "$gte" : ISODate("2017-01-18T05:57:00Z"), 
        "$lte" : ISODate("2017-05-18T06:12:00Z") } } }, 
    { "$group" : { "_id" : { 
    "eventSource" :  "$eventSource" }, 
    "day" : { "$dayOfMonth" : "$timestamp" }, 
    "year" : { "$year" : "$timestamp" } 
    },
    "count" : { "$sum" : 1 } } }]).find({})


assert: command failed: {
"ok" : 0,
"errmsg" : "unknown group operator '$dayOfMonth'",
"code" : 15952,
"codeName" : "Location15952"
} : aggregate failed
_getErrorWithCode@src/mongo/shell/utils.js:23:13
doassert@src/mongo/shell/assert.js:13:14
assert.commandWorked@src/mongo/shell/assert.js:266:5
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1215:5
@(shell):1:1

Any help would be appreciated. 

Thanks


Shiv

unread,
May 18, 2017, 10:39:25 AM5/18/17
to mongodb-user

$dayOfMonth / any other date time operator are not group accumulator. 

So your $group stage should look like

 {
  "$group": {
  "_id": {
  "eventSource": "$eventSource",
  "day": {
  "$dayOfMonth": "$timestamp"
  },
  "year": {
  "$year": "$timestamp"
  }
  },
  "count": {
  "$sum": 1
  }
  }
 },
Reply all
Reply to author
Forward
0 new messages