9

I' trying to use aggregation framework (with ruby) and project the date like this:

db['requests'].aggregate([
{"$project" => {
    _id: 0, 
    method: '$method', 
    user: '$user', 
    year: {'$year' => '$timestamp'}
}}])

the document is like this one:

{
_id: ObjectId("5177d7d7df26358289da7dfd"),
timestamp: ISODate("2013-04-12T03:58:05+00:00"),
method: "POST",
status: "200",
inputsize: "874",
outputsize: "4981",
user: "131"
}

but i get the following error:

Mongo::OperationFailure: Database command 'aggregate' failed: (errmsg: 'exception: can't convert from BSON type EOO to Date'; code: '16006'; ok: '0.0').

This is strange because it works correctly if I run this on the exactly same db which is imported with mongorestore.

Community
  • 1
  • 1
shoen
  • 11,845
  • 4
  • 22
  • 27
  • Apparently the order of the array passed in to aggregate() is important. If you have fields where something is omitted, you'll want to add that into the $match and have the $match be the first element in the array. I.e. > db.user_account.aggregate( [ { $match : { "uts" : { $exists : true }, "chan_key" : "333261c7a72650a95c68d30cd70" } } , { $project : { "period_month": { $month: "$uts" } } }, { $group: { _id : { "period_month" : "$period_month" }, "number" : { $sum : 1 } } } ] ) – Wedge Martin Sep 20 '13 at 15:02

2 Answers2

20

The problem was that I was saving some documents without the timestamp field.

shoen
  • 11,845
  • 4
  • 22
  • 27
2

If you needed to have some documents without this timestamp field, you could try this (I'm using Javascript/Mongoose notation):

year: { $cond: [{ $ifNull: ['$timestamp', 0] }, { $year: '$deliveryDateEnd' }, -1] }

In this case, every document without the timestamp field would return -1. All the other documents would return the year as expected.

FRocha
  • 942
  • 7
  • 11