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

更新時間:2020 年 6 月 16 日

626 次瀏覽

開啟你的 職業生涯

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.