Dante
Dante

Reputation: 61

How to group by two fields mongoDB aggregation

I have the following documents in mongoDB:

{
  _id: "YYYY-MM-DD",
  workedTimes: [
    {..., driver: {username: string} }
  ]
}

Documents in DB

every workedTime has a driver with a userName prop, and i want to group them by date and driver.username with a aggregation but i can't get it

I've tried something like this

$group: {
  "_id": "$workedTimes.driver.username",
  "date": {
    $push: "$_id"
    
  },
  "clocks": {
    $push: {
      "date": "$_id",
      "workedTimes": "$workedTimes"
    }
  }
}

but i cant get the output i want

I want a output something like this

{
  date: 2022-08-24
  username: driver1
  workedTimes: []
},
{
  date: 2022-08-24
  username: driver2
  workedTimes: []
},
{
  date: 2022-08-25
  username: driver1
  workedTimes: []
}

Upvotes: 0

Views: 319

Answers (1)

biorubenfs
biorubenfs

Reputation: 735

Maybe this is what you are looking for:

db.collection.aggregate([
  { // Your other stages here },
  {
    "$unwind": "$workedTimes" // your $unwind stage
  },
  {
    "$group": {
      "_id": {
        _idField: "$_id",
        _driver: "$workedTimes.driver.username"
      },
      "_workedTimes": {
        "$push": "$workedTimes"
      }
    }
  },
  {
    "$project": {
      date: "_id.$_idField",
      driver: "$_id._driver",
      workedTimes: "$_workedTimes",
      _id: 0
    }
  }
])

Maybe the fields syntaxis is a little weird, but I think this works.

Upvotes: 1

Related Questions