如何在 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(),它返回當前本地時間。

更新於: 16-6-2020

626 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.