如何在 MongoDB 中插入 Python 对象?
你可以使用 Python 中的 pymongo 库来连接到 MongoDB 数据库并使用它来插入、更新、删除等 Python 中的对象。该库默认支持 Python datetime 对象,而且你无需做任何特殊操作即可使用 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(),它返回当前本地时间。
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP