Home > Blockchain >  How to use multiple items in group by
How to use multiple items in group by

Time:02-18

I have data like:

[
    {"createdAt": 2022-02-10T00:00:00.000Z,name:'stack',value:'3'}
    {"createdAt": 2022-02-10T00:00:00.000Z,name:'google',value:'30'}
    {"createdAt": 2022-03-10T00:00:00.000Z,name:'stack',value:'33'}
    {"createdAt": 2022-04-10T00:00:00.000Z,name:'google',value:'32'}
    {"createdAt": 2022-03-10T00:00:00.000Z,name:'google',value:'31'}
    {"createdAt": 2022-02-10T00:00:00.000Z,name:'stack',value:'13'}
    {"createdAt": 2022-04-10T00:00:00.000Z,name:'stack',value:'23'}
    {"createdAt": 2022-02-10T00:00:00.000Z,name:'google',value:'33'}
    {"createdAt": 2022-04-10T00:00:00.000Z,name:'google',value:'43'}
    {"createdAt": 2022-03-10T00:00:00.000Z,name:'stack',value:'32'}
    {"createdAt": 2022-02-10T00:00:00.000Z,name:'stack',value:'35'}
    {"createdAt": 2022-04-10T00:00:00.000Z,name:'google',value:'38'}
]

Query

db.collection.aggregate([
    {$group:{_id:{$dayOfYear:"$createdAt",name:"$name"},"total":{$sum:"$value"}}}
])

Expected results:

[
    {name:google,date:2022-02-10:,value:63}
    {name:google,date:2022-03-10:,value:31}
    {name:google,date:2022-04-10:,value:113}
    {name:google,date:2022-02-10:,value:51}
    {name:google,date:2022-03-10:,value:65}
    {name:google,date:2022-04-10:,value:23}
]

I am trying to group by multiple items and getting the following error:

An object representing an expression must have exactly one field: { $dayOfYear: "$createdAt", name: "$name" }

CodePudding user response:

  1. $set - Create date field with date-only string (via $dateToString).
  2. $group - Group by date and name. For summing value as total, you need cast to integer via $int first.
  3. $project - Decorate output document.
db.collection.aggregate([
  {
    $set: {
      date: {
        "$dateToString": {
          "date": "$createdAt",
          "format": "%Y-%m-%d"
        }
      }
    }
  },
  {
    $group: {
      _id: {
        date: "$date",
        name: "$name"
      },
      "total": {
        $sum: {
          $toInt: "$value"
        }
      }
    }
  },
  {
    $project: {
      _id: 0,
      date: "$_id.date",
      name: "$_id.name",
      total: "$total"
    }
  }
])

Sample Mongo Playground

  • Related