当前位置: 首页 > 新闻动态 > 技术教程

如何在 Mongodb 中插入 Python 对象?

作者:PHPz 浏览: 发布日期:2023-09-02
[导读]:您可以使用Python中的pymongo库连接到MongoDB数据库并使用它在Python中插入、更新、删除等对象。该库支持开箱即用的Python日期时间对象,您无需执行任何特殊操作即可使用PyMongo在Mongo中插入日期。例如,示例frompymongoimportMongoClient#ThiswilltrytoconnecttoMongoDBonthedefaultportandhostclient=MongoClient()db=client.test_database#Insert

您可以使用Python中的pymongo库连接到MongoDB数据库并使用它在Python中插入、更新、删除等对象。该库支持开箱即用的 Python 日期时间对象,您无需执行任何特殊操作即可使用 PyMongo 在 Mongo 中插入日期。例如,

示例

from pymongo import MongoClient
# This will try to connect to MongoDB on the default port and host
client = MongoClient()
db = client.test_database
# Insert the given dictionary to the objects collection:
result = db.objects.insert_one({"last_modified": datetime.datetime.utcnow()})
print("Object inserted!")

输出

这将给出输出 -

Object inserted!

注意 - 始终使用 datetime.datetime.utcnow(),它返回 UTC 中的当前时间,而不是 datetime.datetime.now(),它返回当前本地时间。

免责声明:转载请注明出处:http://sczxchw.cn/news/513383.html

扫一扫高效沟通

多一份参考总有益处

免费领取网站策划SEO优化策划方案

请填写下方表单,我们会尽快与您联系
感谢您的咨询,我们会尽快给您回复!