且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mongodb:基于ISODate格式的时间查询

更新时间:2021-08-28 15:57:25

一种方法是使用 聚合框架 ,尤其是 $ redact 操作符,它根据值剥离内容的文档流在文件及其子文件中。根据布尔表达式的结果,可以从流中修剪文档,在其子文档也被检查之后包含在流中,或者刚刚被传递到流中。 $ refact 是从流中轻松删除敏感信息。

One approach is to use the aggregation framework, in particular the $redact operator which strips the document stream of content based on values within the document and its sub-documents. Depending on the result of a boolean expression, a document can be pruned from the stream, be included in the stream after its sub-documents have also been checked, or just passed complete into the stream. The idea behind $redact is to make the removal of sensitive information from the stream easy.

在您的情况下,条件表达式使用 $ cond 运算符和 $和 布尔运算符表示时间范围与比较运算符之间的逻辑AND $ gt $ lt 。使用 $ hour date运算符将日期字段的小时作为0到23之间的数字返回。因此,您的最终聚合看起来像这样:

In your case, the criteria expression uses the $cond operator and the $and boolean operator to express the logical AND between the time ranges with the comparison operators $gt and $lt. Use the $hour date operator to return the hour for the date field as a number between 0 and 23. Thus your final aggregation looks like this:

db.collection.aggregate([
    {
        "$redact": {
            "$cond": {
                "if": { 
                    "$and": [
                        { "$gt": [ {"$hour": "$date"}, 4] },
                        { "$lt": [ {"$hour": "$date"}, 8] }
                    ]                 
                },
                "then": "$$KEEP",
                "else": "$$PRUNE"
            }
        }        
    }
])

示例输出:

/* 0 */
{
    "result" : [ 
        {
            "_id" : ObjectId("56404450472fe25cc6b85886"),
            "date" : ISODate("2015-11-09T05:58:19.474Z")
        }, 
        {
            "_id" : ObjectId("56404450472fe25cc6b85887"),
            "date" : ISODate("2014-10-25T07:30:00.241Z")
        }
    ],
    "ok" : 1
}