Query mongoDB for a date between two dates misses some documents

白昼怎懂夜的黑 提交于 2021-01-28 18:02:46

问题


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.

Here is the query:

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

回答1:


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

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"
    }  
})

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

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


来源:https://stackoverflow.com/questions/53250093/query-mongodb-for-a-date-between-two-dates-misses-some-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!