RisingStar
RisingStar

Reputation: 63

MongoDB calculate date between 2 fields in document

I have a collection that each document have 2 fields of dates (start date/ end date) And I want to return documents that the diff between the end date and the start date its in the least 30 minutes. Thanks!

Upvotes: 1

Views: 741

Answers (1)

Bertrand Martel
Bertrand Martel

Reputation: 45352

You can use an aggregation with a single $redact stage and use $subtract to calculate difference between 2 dates :

var dateSchema = new mongoose.Schema({
    startDate: Date,
    endDate: Date
}, { collection: "dates" });

var DateModel = db.model('DateModel', dateSchema);

DateModel.aggregate({
    $redact: {
        $cond: {
            if: { $gte: [{ $subtract: ["$endDate", "$startDate"] }, 30 * 60 * 1000] },
            then: "$$KEEP",
            else: "$$PRUNE"
        }
    }
}, function(err, res) {
    console.log(res);
})

Upvotes: 1

Related Questions