0
votes

I have the following Data in Mongo and trying to group searches by day. So I know how many searches happen each day

{
    "_id" : ObjectId("5ee3ebb8a18fae0001cdf0c6"),
    "term" : "wp-login.php",
    "Date" : ISODate("2020-06-12T20:55:20.335Z")
}

I have the following query

db.search.aggregate(
  {
    $project: {
      year: {$year: Date},
      month: {$month: Date},
      dayOfMonth: {$dayOfMonth: Date}
    }
  },
  {
    $group: {
      _id: {
        year: '$year',
        month: '$month',
        dayOfMonth: '$dayOfMonth'
      },
      count: {
        $sum: 1
      }
    }
  }
)

And I get the following error

Failed to execute script.

Error: command failed: { "ok" : 0, "errmsg" : "Failed to optimize pipeline :: caused by :: can't convert from BSON type javascript to Date", "code" : 16006, "codeName" : "Location16006" } : aggregate failed Details: _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:18:14 _assertCommandWorked@src/mongo/shell/assert.js:534:17 assert.commandWorked@src/mongo/shell/assert.js:618:16 DB.prototype._runAggregate@src/mongo/shell/db.js:260:9 DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1062:12 DBCollection.prototype.aggregate@:1:355 @(shell):1:1

1

1 Answers

2
votes

Use "$Date" instead of Date

db.collection.aggregate({
  $project: {
    year: {
      $year: "$Date"
    },
    month: {
      $month: "$Date"
    },
    dayOfMonth: {
      $dayOfMonth: "$Date"
    }
  }
},
{
  $group: {
    _id: {
      year: "$year",
      month: "$month",
      dayOfMonth: "$dayOfMonth"
    },
    count: {
      $sum: 1
    }
  }
})

You can refer to the example here