1
votes

I am getting this exception from Mongodb Aggregation operation:

can't convert from BSON type String to Date (16006)).

I see other questions on the same topic but I am very much sure that the field "date" in the following code is saved as Date type field. Here is what I am trying to do:

db.schemes.aggregate([
  {"$project": {
      date_day: {$dayOfMonth: "$date"}, 
      date_month: {$month: "$date"}, 
      date_year: {$year: "$date"},
      net_asset: "$net_asset"
  }},
  {"$match": {scheme_code: "ABC"}},
  {$group: {
    _id: {
      date_month: "$date_month", 
      date_year: "$date_year"}, 
      net_asset: {$first: "$net_asset"}, 
      day_date: {$first: "$date_day"}
    }
  }
])

Here is a sample document:

db.schemes.findOne()
{
    "_id": ObjectId("586a87d5ab0de166ea000001"),
    "scheme_code": "H01",
    "scheme_name": "ABC",
    "date": ISODate("2016-12-28T00:00:00Z"),
    "net_asset": 48.452,
    "updated_at": ISODate("2017-01-02T17:03:17.264Z"),
    "created_at": ISODate("2017-01-02T17:03:17.264Z")
}

Also please note that the error doesn't occur if last group operator is removed so it has something to do with that.

Any pointers on how to go about debugging this one would be appreciated.

Thanks.

1
Hi Ishu; can I make two requests? Could you post an example of the equivalent aggregation in the mongo shell as well? That would be easier for non-rails users to understand. Secondly, could you post an example of a document you are aggregating, to let everybody see with certainty what the fields and datatypes are? - Vince Bowdren
Hi @VinceBowdren Just added the Mongo Reference. Also please note that everything works well if I remove the last group operator. However, group is very essential to my requirements. Editing the post for the example document in a moment. - Ishu

1 Answers

1
votes

Placing Match before the project fixed the issue.