0

Given the following schema, I want to write a MongoDB scheme to find all schemes with duration of more than a year. ie (start - end) > 1 year. I am not sure if I can specify such an expression in mongodb query (start - end) > 1 year.

{
    "update" : ISODate("2017-09-26T15:22:13.172Z"),
    "create" : ISODate("2017-09-26T15:22:13.172Z"),
    "scheme" : {
        "since" : ISODate("2017-09-26T15:22:13.172Z"),
        "startDate":  ISODate("2017-09-26T15:22:13.172Z"),
        "endDate":  ISODate("2018-09-26T15:22:13.172Z"),
    },
}
JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • 2
    Possible duplicate of [MongoDb query condition on comparing 2 fields](https://stackoverflow.com/questions/4442453/mongodb-query-condition-on-comparing-2-fields) – s7vr Sep 29 '17 at 01:55

1 Answers1

0

You can use aggregation with subtract:

db.yourcollection.aggregate(
[{ 
    $project : { dateDifference: { $subtract: [ "$scheme.endDate", "$scheme.endDate" ] }},
    $match : { "$dateDifference" : { $gt :  31536000000 } } 
}]);

(* 31536000000 = milliseconds per year)

You may use another $project to output any fields you need in the matching documents.

Pubudu Jayawardana
  • 2,250
  • 1
  • 13
  • 18