title: MongoDB Aggregate Query Group by Dates
body: <p>I have the following collection in mongoDB</p>
  
  <pre><code>{ _id, startTime, duration }
  </code></pre>
  
  <p>So the basic idea is that a camera looks out for people and once it detects a person it saves the startTime and once a person disappears it saves the duration. 
  So the entity basically says "A person appeared at X time and was in the camera range for Y milliseconds". Both startTime and duration are numeric values.</p>
  
  <p>So, I want to perform various queries like: 
  1. Give me the number of people per month/year 
  2. Give me the number of people per month with duration > 5000ms</p>
  
  <p>etc.</p>
  
  <p>I'm fairly new to MongoDB though and I have a bit of trouble with the aggregation framework, so I would appreciate if someone gives me an idea of how to do a query such as the above, in order to get some sort of head start.</p>
  
  <p>EDIT:</p>
  
  <p>Ok I have done a couple of tries but no luck. Right now my objects have this form:</p>
  
  <pre><code>{
    "_id" : ObjectId("52de407c75895eaf5ea99715"),
    "startTime" : "new Date('02 01 2011 08:36:54')",
    "duration" : 27000
  }
  </code></pre>
  
  <p>and I'm trying this query:</p>
  
  <pre><code> db.collection.aggregate(
          {$project : {
               year : {$year : "$startTime"}
  
          }},
          {$group : {
               _id : {year : "$year"}, 
               count : {$sum : 1}
          }}
      )
  </code></pre>
  
  <p>but I'm getting the following exception: </p>
  
  <pre><code>Error occurred in performing aggregation
  Command 'aggregate' failed: exception: can't convert from BSON type String to Date (response: { "errmsg" : "exception: can't convert from BSON type String to Date", "code" : 16006, "ok" : 0.0 })
  Type: MongoDB.Driver.MongoCommandException
  Stack:    at MongoDB.Driver.Operations.CommandOperation`1.Execute(MongoConnection connection)
     at MongoDB.Driver.MongoCollection.RunCommandAs[TCommandResult](IMongoCommand command, IBsonSerializer resultSerializer, IBsonSerializationOptions resultSerializationOptions)
     at MongoDB.Driver.MongoCollection.RunCommandAs[TCommandResult](IMongoCommand command)
     at MongoDB.Driver.MongoCollection.Aggregate(IEnumerable`1 operations)
     at MangoUI.ComAggregate.kRemove_Click(Object sender, EventArgs e)
  Inputs:: 
  Command:  aggregate
  Ok:       False
  ErrorMsg: exception: can't convert from BSON type String to Date
  Request:  { "aggregate" : "person", "pipeline" : [{ "$project" : { "year" : { "$year" : "$startTime" } } }, { "$group" : { "_id" : { "year" : "$year" }, "count" : { "$sum" : 1 } } }] }
  Response: { "errmsg" : "exception: can't convert from BSON type String to Date", "code" : 16006, "ok" : 0.0 }
  </code></pre>