查询 mongoDB 中两个日期之间的日期遗漏了一些文档 [英] Query mongoDB for a date between two dates misses some documents

查看:44
本文介绍了查询 mongoDB 中两个日期之间的日期遗漏了一些文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在集合名称 chats 中有以下文档:

I have the following document in a collection name chats:

{
    "_id" : 25281,
    "conversation" : [ 
        {
            "time" : "1970-01-18T20:16:28.988Z"
        }, 
        {
            "time" : "2018-11-09T18:43:09.297Z"
        }
    ],
}

由于某种原因,此特定文档未在以下查询中返回,尽管类似文档按预期返回.

For some reason this specific document is not returning in the below query, although similar documents are returning as expected.

这是查询:

db.getCollection('chats').find({"conversation.1.time": 
    { 
        "$gte": ISODate("2018-11-09T00:00:00.000Z"), 
        "$lt": ISODate("2018-11-10T00:00:00.000Z")
    }  
})

推荐答案

此文档不匹配,因为您的查询中指定的 ISODate 与您的查询中的 string 不匹配数据模型.MongoDB 在值之前检查类型,所以这就是为什么你没有得到值的原因.来自 docs

This document is not matched because there's a mismatch between ISODate specified in your query and string in your data model. MongoDB checks types before values so that's why you're getting no values. From docs

然而,对于大多数数据类型,比较运算符仅对目标字段的 BSON 类型与查询操作数的类型匹配的文档执行比较.

For most data types, however, comparison operators only perform comparisons on documents where the BSON type of the target field matches the type of the query operand.

有三种方法可以解决这个问题.您可以更改查询中的类型:

There are three ways to fix that. You can change the type in your query:

db.getCollection('chats').find({"conversation.1.time": 
    { 
        "$gte": "2018-11-09T00:00:00.000Z", 
        "$lt": "2018-11-10T00:00:00.000Z"
    }  
})

或者你需要转换chats中的数据:

or you need to convert the data in chats:

{
    "_id" : 25281,
    "conversation" : [ 
        {
            "time" : ISODate("1970-01-18T20:16:28.988Z")
        }, 
        {
            "time" : ISODate("2018-11-09T18:43:09.297Z")
        }
    ],
}

或者你可以看看 $toDate 运算符(在 MongoDB 4.0 中引入):

Alternatively you can take a look at $toDate operator in Aggregation Framework (introduced in MongoDB 4.0):

db.getCollection('chats').aggregate([
    {
        $addFields: {
            value: { $arrayElemAt: [ "$conversation", 1 ] }
        }
    },
    {
        $match: {
            $expr: {
                $and: [
                    { $gte: [ { $toDate: "$value.time" }, ISODate("2018-11-09T00:00:00.000Z") ] },
                    { $lt: [ { $toDate: "$value.time" }, ISODate("2018-11-10T00:00:00.000Z") ] },
                ]
            }
        }
    }
])

这篇关于查询 mongoDB 中两个日期之间的日期遗漏了一些文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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