我似乎不能得到甚至是最基本的日期查询工作在MongoDB。使用类似这样的文档:

{
    "_id" : "foobar/201310",
    "ap" : "foobar",
    "dt" : ISODate("2013-10-01T00:00:00.000Z"),
    "tl" : 375439
}

查询如下所示:

{ 
    "dt" : { 
        "$gte" : { 
            "$date" : "2013-10-01T00:00:00.000Z"
        }
    }
}

执行得到0个结果:

db.mycollection.find({
  "dt" : { "$gte" : { "$date" : "2013-10-01T00:00:00.000Z"}}
})

知道为什么不行吗?

作为参考,这个查询是由Spring的MongoTemplate生成的,所以我不能直接控制最终发送到MongoDB的查询。

(注:)

> db.version()
2.4.7

谢谢!


当前回答

老问题,但仍然是第一个谷歌击中,所以我张贴在这里,所以我发现它再次更容易…

使用Mongo 4.2和一个aggregate():

db.collection.aggregate(
    [
     { $match: { "end_time": { "$gt": ISODate("2020-01-01T00:00:00.000Z")  } } },
     { $project: {
          "end_day": { $dateFromParts: { 'year' : {$year:"$end_time"}, 'month' : {$month:"$end_time"}, 'day': {$dayOfMonth:"$end_time"}, 'hour' : 0  } }
     }}, 
     {$group:{
        _id:   "$end_day",
        "count":{$sum:1},
    }}
   ]
)

这个函数将groupby变量作为日期,有时更好的方法是将其作为组件本身。

其他回答

在json严格模式下,你必须保持以下顺序:

{
    "dt": {
        "$gte": {
            "$date": "2013-10-01T00:00:00.000Z"
        }
    }
}

唯一的一件事是在mlab.com上定义我的搜索查询。

试试这个:

{ "dt" : { "$gte" : ISODate("2013-10-01") } }

在MongoDB shell中:

db.getCollection('sensorevents').find({from:{$gt: new ISODate('2015-08-30 16:50:24.481Z')}})

在我的nodeJS代码中(使用Mongoose)

    SensorEvent.Model.find( {
        from: { $gt: new Date( SensorEventListener.lastSeenSensorFrom ) }
    } )

我正在查询我的传感器事件集合,以返回'from'字段大于给定日期的值

当我在搜索小于或等于现在的值时,这个方法很管用:

db.collectionName.find({ "dt": { "$lte" : new Date() + "" } });

我使用robomongo作为mongodb客户端gui,下面为我工作

db.collectionName.find({"columnWithDateTime" : {
$lt:new ISODate("2016-02-28T00:00:00.000Z")}})

On the app side I am using nodejs based driver mongodb(v1.4.3),the application uses datepicker in the ui which gives date like YYYY-mm-dd, this is then appended with default time like 00:00:00 and then given to the new Date() constructor and then supplied to the mongodb criteria object,I think the driver converts the date to ISO date and the query then works and gives desired output, however the same new Date() constructor does not work or show same output on robo mongo,for the same criteria,which is weird,since I used robomongo to cross check my criteria objects.

而默认的cli mongoshell与ISODate和new Date()都能很好地工作