Terrence
Terrence

Reputation: 1022

Why doesn't this Mongo aggregation work?

I feel like I must be missing something obvious. Here is the aggregation, as one would post it in the shell:

db.documents.aggregate(
   { $project: { title: 1, "date.year": 1, decade:
   { $subtract: ['$date.year', { $mod: ['$date.year', 10]}]}
}})

This is supposed to take a list of documents, each with a date.year field, and add a decade field indicating which decade the document is in (1900, 1910, etc.) I'm planning on further transforming the data after I get that added.

The problem is that when I run the aggregation, I get:

{
    "errmsg" : "exception: $subtract resulted in a non-numeric type",
    "code" : 16413,
    "ok" : 0
}

If I change $subtract to $add, it works fine (but doesn't give me the right result, of course.) So what's going on with the subtraction? Why am I getting a non-numeric type when I subtract but a number when I add?

Thanks in advance!

Upvotes: 0

Views: 1322

Answers (1)

Asya Kamsky
Asya Kamsky

Reputation: 42352

This looks like a bug in the aggregation framework - it's not handling subtraction correctly when the fields you are operating for are not set in the documents going through the pipeline.

It's been fixed in 2.3.2 (I can't reproduce this - it projects "null" when "date" is not set) but one way you can work around this limitation is by adding a $match condition to your pipeline, i.e. prefix {$project} with:

{$match: {"date.year":{$exists:true}}}

Upvotes: 3

Related Questions