简体   繁体   English

Pymongo 查询日期失败

[英]Pymongo Query for Date is failing

I have a query that works fine in mongodb compass, but the moment I bring it over into Jupyter it breaks.我有一个在 mongodb 指南针中运行良好的查询,但是当我把它带入 Jupyter 时它就坏了。 The issue is something to do with the date filter.问题与日期过滤器有关。

I have tried both:我都试过了:

cursor = prod_db.my_collection.find({"date": {"$eq": "new Date('2021-04-26')"}, "type": "Regular"})

as well as

cursor = prod_db.my_collection.find({"date": "new Date('2021-04-26')", "type": "Regular"})

If I remove the date query, I get a return that I would expect, which validates that the db connection is set up properly and that the "type" filter is valid.如果我删除日期查询,我会得到我期望的返回,它验证数据库连接设置正确并且“类型”过滤器有效。 What am I missing here?我在这里想念什么?

new Date is the date keyword for MongoShell. new Date是 MongoShell 的日期关键字。 You should replace it with python's built-in datetime package.您应该用 python 的内置datetime时间 package 替换它。

from datetime import datetime
cursor = prod_db.my_collection.find({"date": datetime(2021, 4, 26), "type": "Regular"})

Issues mapping date columns across python and Mongo happens primarily because Mongo stores the date as a JavaScript date object and then wraps the ISODate format around it.跨 python 和 Mongo 映射日期列的问题主要是因为 Mongo 将日期存储为 JavaScript 日期 object 然后围绕它包装 ISODate 格式。 However if the date values that we are trying to pass from python onto mongo is in datetime format ( like @hhharsha36 mentioned above) one should be good但是,如果我们试图从 python 传递到 mongo 的日期值是日期时间格式(如上面提到的@hhharsha36),那么一个应该很好

I found this article helpful when I was going through some hellish time using dates from pandas and python variables and using that to query/insert/update in Mongo: ( https://medium.com/nerd-for-tech/how-to-prepare-a-python-date-object-to-be-inserted-into-mongodb-and-run-queries-by-dates-and-range-bc0da03ea0b2 )当我使用 pandas 和 python 变量中的日期并使用它在 Mongo 中查询/插入/更新时,我发现这篇文章很有帮助: -prepare-a-python-date-object-to-be-inserted-into-mongodb-and-run-queries-by-dates-and-range-bc0da03ea0b2 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM