1

How can I use a field that I just added in the $addFields stage to the following $match stage?

This will return no result:

db.getCollection('myCollection').aggregate([
  {$addFields: { "test": ISODate("2018-02-15T03:22:21.000Z")}},
  {$match: { $or: [{"timestamp":"$test"}]}}
])

This one will return expected result:

db.getCollection('myCollection').aggregate([
  {$addFields: { "test": ISODate("2018-02-15T03:22:21.000Z")}},
  {$match: { $or: [{"timestamp":ISODate("2018-02-15T03:22:21.000Z")}]}}
])

How comes that the $test is not resolved in the $match stage?

EDIT I finally post myself a solution for mongdb 2.4 thanks to this answer. Solutions are similar but the problem are not expressed the same way

1 Answers1

0

I think Veeram answer is valid for mongodb version 3.6 but I'm running with version 3.4

I finally found this way to be able to use a field added in a $addFields stage:

db.getCollection('myCollection').aggregate([
  {$addFields: { "myDate": ISODate("2018-02-15T03:22:21.000Z")}},
  {$project:{test: {$cond:[{$eq:["$timestamp", "$myDate"]},1,0]}}},
  {$match: {"test": {"$eq": 1}}}
])

or with the $redact stage:

db.getCollection('myCollection').aggregate([
  {$addFields: { "test": ISODate("2018-02-15T03:22:21.000Z")}},
  {$redact: {$cond: [{ $eq: [ "$timestamp", "$test" ] }, "$$KEEP", "$$PRUNE"]}}
])

I do not know why it is working with (addFields + project + match) and with (addFields + redact) but not with (addFields + match) but I will go with this solution as migration is not yet foreseen