Mongodb获取日期之间的文档(以字符串形式存储,格式为"20-05-2019") [英] Mongodb get documents between dates(Stored as string in the format "20-05-2019")

查看:224
本文介绍了Mongodb获取日期之间的文档(以字符串形式存储,格式为"20-05-2019")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的示例文档:

{ 
  "timestamp" : "1558341279777",
  "date" : "20-05-2019",
  "hour" : "14",
  "month" : "5",
  "time" : "14:4:39",
  "weekDay" : "Monday"
}

我想查询给定日期之间的文档.请在"26-05-2019"和"01-06-2019"之间说.
以下是我尝试过的查询:

I want to query documents between given dates. Say between "26-05-2019" and "01-06-2019".
The following is the query that I tried:

db.getCollection('messagelogs').find({'date': {'$gte': '20-05-2019', '$lt': '31-05-2019'}})  

上述查询的问题在于它会进行字符串比较,当我们查询日期时,它并不总是返回正确的结果.有一种干净的方法可以做到这一点吗?

The problem with the above query is that it does string comparison, which doesnt always return the correct result when we query for dates. Is there a clean way to do this?

推荐答案

请尝试以下操作:

    db.collection.find({
      "$expr": {
        "$and": [
      {
        "$gte": [
          { "$dateFromString": { "dateString": "$date, "format": "%m-%d-%Y" }},
          ISODate("2019-05-26T00:00:00Z")
        ]
      },
      {
        "$lte": [
          { "$dateFromString": { "dateString": "$date", "format": "%m-%d-%Y" }},
          ISODate("2019-06-15T23:59:59Z")
        ]
      }
    ]
     }
    })

这篇关于Mongodb获取日期之间的文档(以字符串形式存储,格式为"20-05-2019")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆