Mongodb : ISODate格式的时间查询。我的查询有什么问题?

Mongodb : Query based on time in ISODate format. What's wrong in my query?

假设Mongodb数据库中的样本文档如下:

 { "date" : ISODate("2015-11-09T05:58:19.474Z") }
 { "date" : ISODate("2014-10-25T07:30:00.241Z") }
 { "date" : ISODate("2015-11-30T15:24:00.251Z") }
 { "date" : ISODate("2012-01-10T18:36:00.101Z") }

预计:

 { "date" : ISODate("2015-11-09T05:58:19.474Z") }
 { "date" : ISODate("2014-10-25T07:30:00.241Z") }

我尝试了以下查询:

 collection.find({"$and": [{ "date" : { "$gt": [ {"$hour": "$date"}, 4] } }, 
                           {"date" :{ "$lt": [ {"$hour": "$date"}, 8] } } 
                 ]}); 

此查询未产生任何结果。 中接受的答案在哪里。我哪里错了?

注意:我正在使用 nodejs 连接到 mongodb

查询没有产生任何结果,因为 $hour operator is only applied in the aggregation pipeline, not the find() query. So in your aggregation your pipeline has two steps, the $project which creates a new field that holds the hour part and the next stage $match 然后查询文档。

因此您最终的聚合操作将是这样的:

var pipeline = [
    {
        "$project": {
            "hour": { "$hour": "$date" },
            "date": 1
        }
    },
    {
        "$match": {
            "hour": { "$gt": 4,  "$lt": 8}
        }
    }
]

db.collection.aggregate(pipeline);