twux
twux

Reputation: 35

mongodb group one _id different key names / $dateToString two data fields

My mongo collection has documents with the key tracking.timestamp and other documents with tracking.soi_timestamp. Is there a way to use both keys to $group in one _id as a new combined_timestampfield field?

_id: {
 "date": {
   "$dateToString": {
        "format": "%Y-%m-%d", 
        "date": "$tracking.combined_timestampfield"
  }
}

Update sample documents:

{
  "tracking": {
    "timestamp": {
      "$date": "2020-06-02T05:33:10.000Z"
    }
  }
}

...

{
  "tracking": {
    "soi_timestamp": {
      "$date": "2020-06-02T14:23:00.000Z"
    }
  }
}

desired output:

{
  "_id": {
    "date": "2020-06-02"
  },
  "total": 2
}

Upvotes: 1

Views: 275

Answers (1)

ambianBeing
ambianBeing

Reputation: 3529

Use either $project or $addFields to pick either soi_timestamp and timestamp into a common name field using $ifNull operator, lets say actualTimeStamp at the document level.

Then $group the documents by this new projected/added field:

Query:

db.collection.aggregate([
  {
    $addFields: {
      "actualTimeStamp": {
        $ifNull: [
          "$tracking.soi_timestamp",
          "$tracking.timestamp"
        ]
      }
    }
  },
  {
    $group: {
      _id: {
        "date": {
          $dateToString: {
            format: "%Y-%m-%d",
            date: "$actualTimeStamp"
          }
        }
      },
      count: {
        $sum: 1
      }
    }
  }
])

OUTPUT:

[
  {
    "_id": {
      "date": "2020-06-02"
    },
    "count": 2
  }
]

Play Link

Upvotes: 1

Related Questions