Mongodb:基于时间的ISODate格式查询。我的查询出了什么问题? [英] Mongodb : Query based on time in ISODate format. What's wrong in my query?

查看:156
本文介绍了Mongodb:基于时间的ISODate格式查询。我的查询出了什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设Mongodb数据库中的示例文档如下:

Suppose the sample documents in Mongodb database are as follows:

 { "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] } } 
                 ]}); 

此查询未产生任何结果。作为> Mongodb:基于时间的ISODate格式的查询可以。我在哪里错了?

This query is not yielding any results. Where as the accepted answer in Mongodb : Query based on time in ISODate format does. Where I am wrong?

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

Note: I am using nodejs to connect to mongodb

推荐答案

查询未产生任何结果,因为 $ hour 运算符仅应用于聚合管道,而不应用于 find()查询。因此,在汇总中,您的管道有两个步骤, $ project ,它将创建一个新字段,其中包含小时部分和下一阶段 $ match 然后查​​询文档。

The query is not yielding any results because the $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 which then queries the documents.

因此,您最终的汇总操作将如下所示:

Thus your final aggregation operation will be like this:

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

db.collection.aggregate(pipeline);

这篇关于Mongodb:基于时间的ISODate格式查询。我的查询出了什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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