Search code examples
mongodbmongodb-queryaggregation-framework

Mongo query aggregate with a conditional group and another field


I followed this post by @Blakes-Seven Mongodb aggregate $group for multiple date ranges

But I need to add an additional group by field "$User.Account" and I keep getting an error. When I take that out it works fine.

What I'm trying to do and I'm pretty sure the below won't do it is find the top N users within each of the date ranges...

{
    "message" : "the group aggregate field 'User' must be defined as an expression inside an object",
    "ok" : 0,
    "code" : 15951,
    "name" : "MongoError"
}

Any help would be greatly appreciated. I'm missing something...

>     // work out dates somehow var today = new Date(),
>     oneDay = ( 1000 * 60 * 60 * 24 ),
>     ninetyDays = new Date( today.valueOf() - ( 90 * oneDay ) ),
>     sixtyDays = new Date( today.valueOf() - ( 60 * oneDay ) ),
>     thirtyDays = new Date( today.valueOf() - ( 30 * oneDay ) );
> 
> db.logs.aggregate([
>     { "$match": {
>         "DateTime": { "$gte": ninetyDays },
>         "Orgname": /Inc/
>     }},
>     { "$group": {
>         "_id": {
>             "$cond": [
>                 { "$lt": [ "$DateTime", sixtyDays ] },
>                 "61-90",
>                 { "$cond": [
>                     { "$lt": [ "$DateTime", thirtyDays ] },
>                     "31-60",
>                     "01-30"
>                 ]}
>             ]
>         },
>         "User": "$User.Account",
>         "count": { "$sum": 1 },
>     }},
>     {    $sort: {"count": -1}
>     },
>     { $limit: 25} ])

Sample output
01-30  usera 45
01-30  userc 34
01-30  userf 28
01-30  userq 13
… 20 more rows...
01-30  usery 4
31-60  userb 55
… 23 more rows
31-60  userk 3
61-90  userm 78
61-90  userf 45
... 22 more rows...

61-90  usery 22

Solution

  • You can follow below syntax to add another field in $group expression

    db.logs.aggregate([
      { "$match": {
        "DateTime": { "$gte": ninetyDays },
        "Orgname": /Inc/
      }},
      { "$group": {
        "_id": {
          "User": "$User.Account",
          "date": {
            "$cond": [
              { "$lt": [ "$DateTime", sixtyDays ] },
              "61-90",
              { "$cond": [
                { "$lt": [ "$DateTime", thirtyDays ] },
                "31-60",
                "01-30"
              ]}
            ]
          }
        },
        "count": { "$sum": 1 },
      }},
      { "$sort": { "count": -1 }},
      { "$limit": 25}
    ])