Jake Sellers
Jake Sellers

Reputation: 2439

Mongodb aggregate match on dates

I'm running an aggregate query, and after a few projections, I end up with documents that look like

{ _id: 561bed08f8f068cd237a3dc1,
updateDate: Mon Oct 12 2015 11:25:28 GMT-0600 (MDT),
manager: 561bdd37f8f068cd237a3da2,
viewDate: Mon Oct 26 2015 09:02:57 GMT-0600 (MDT) }

Please note, those dates are the console formatted output, when inspected with mongohub, the dates look like new Date(<timestamp>).

I want to match documents where the updateDate is greater than the viewDate, so I have this match:

$match: {
    updateDate: { "$gt": new Date("$viewDate") }
}

However, it returns documents such as the one above, the updateDate is on the 12th, and the viewDate is on the 26th.

I have tried a few variations, with and without the new Date() for example.

Upvotes: 1

Views: 1976

Answers (1)

Sede
Sede

Reputation: 61225

You can't use the $match operator here. You need to use the $redact operator.

db.collection.aggregate([
    { "$redact": { 
        "$cond": [ 
           { "$gt": ["$updateDate", "$viewDate"] }, 
           "$$KEEP", 
           "$$PRUNE"
        ]
    }}
])

Upvotes: 2

Related Questions