简体   繁体   中英

Mongoose - Search dates stored as strings by date range

I have a mongo db with a paymentDate field stored as strings YYYY-MM-DD (I can't change how these are unfortunately), and I need to do a date range search on them.

I found a post suggesting something like this:

coll.find({paymentDate: new RegExp("^(2016-02-18|2016-06-19)", "i")});

But I can't seem to get that to work at all.

Any help is appreciated, I've hit a dead end here.

在这种情况下,以YYYY-MM-DD格式将日期存储为字符串是可行的,因为字符串顺序与日期顺序匹配,因此您可以执行以下操作:

coll.find({paymentDate: {$gte: "2016-02-18", $lte: "2016-06-19"}});

Your first objective should be changing the schema and use Date instead of String . But if it's really not possible and you can't think of a really complicated RegEx , you can do it with Javascript using $where , but it's performance will be much slower:

db.test.find({
    $where: function () {
        var docDate = new Date(this.paymentDate);
        return (docDate >= new Date('2016-02-18') && docDate <= new Date('2016-02-19'))
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM