【问题标题】:MongoShell db query of string date is not working字符串日期的 Mongo Shell db 查询不起作用
【发布时间】:2019-10-15 20:36:44
【问题描述】:

我正在尝试在 date_recorded 字段上查询我的数据库,但查询结果为零。我正在使用 MongoShell,并且在 Compass 中也尝试过。


我尝试了 ISODateDate$eq 变体:

db.my_collection.find({ "date_recorded": { "$eq":  new ISODate("2017-06-09T01:27:33.967Z") }}).count()


我还尝试了 ISODateDate$gte 变体:

db.my_collection.find({ "date_recorded": { "$gte":  new Date("2017-06-09T01:27:33.967Z") }}).count()


记录在数据库中,注意突出显示的字段

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    就像@JohnnyHK 所说,date_recorded 是一个字符串。要进行比较,我们要么需要将date_recorded 转换为日期,要么将其与字符串进行比较。

    以下查询可以得到我们预期的输出:

    db.my_collection.find({ 
        "date_recorded": { 
            $eq:"2017-06-09T01:27:33.967Z" 
        }
    }).count()
    
    db.my_collection.find({ 
        $expr:{
            $eq:[
                {
                    $toDate:"$date_recorded"
                },
                new ISODate("2017-06-09T01:27:33.967Z")
            ]
        }
    }).count()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      相关资源
      最近更新 更多