[英]MongoDB push to nested array or insert new document
我正在為 Mongo (pymongo) 使用 python 庫,我的文檔如下所示:
{"vendor_id": 12, "title": "xyz", "price": 1499.0, "price_history": [{"date": "2019-12-01", "price": 1890.0}]}
如果存在 id=12 的文檔,我想將新的價格對象推送到“price_history”數組。 如果不是,我將創建一個與粘貼的代碼看起來相同的新文檔。
看起來很簡單,但我檢查了多個 stackoverflow 主題和 mongodb 文檔,但無法理解:/
我想出了代碼:
db.holidays.update_one(
{"vendor_id": t["vendor_id"]},
{"$push": {"price_history": t["price_history"][0]}},
upsert=True
)
但是當找不到文檔時,它只插入 vendor_id 而不是整個文檔。
有小費嗎? 感謝您花時間解決我的問題。
$setOnInsert
來救援:
db.holidays.update(
{ "vendor_id": t["vendor_id" }, // Query parameter
,{ // Update document
"$push": {"price_history": t["price_history"][0]},
"$setOnInsert": { everything else you want insert besides the push and the vendor_id
}
,{ upsert: true } // Options
)
將記錄提取到 dict 中並使用標准 python 進行操作。 如果您使用find_one()
並且沒有匹配項,它將返回None
from pymongo import MongoClient
from bson.json_util import dumps
db = MongoClient()["testdatabase"]
# Data setup
db.testcollection.delete_many({})
template = {"vendor_id": 12, "title": "xyz", "price": 1499.0, "price_history": []}
data_setup = {"vendor_id": 12, "title": "xyz", "price": 1499.0,
"price_history": [{"date": "2019-12-01", "price": 1890.0}]}
new_price = {"date": "2019-12-02", "price": 2000.0}
# Comment the next line out to see what happens if the record isn't present
db.testcollection.insert_one(data_setup)
record = db.testcollection.find_one({"vendor_id": 12})
if record is None:
record = template
record['price_history'].append(new_price)
db.testcollection.replace_one({"vendor_id": 12}, record, upsert=True)
# Pretty up the record output
print(dumps(db.testcollection.find_one({}, {'_id': 0}), indent=4))
給出:
{
"vendor_id": 12,
"title": "xyz",
"price": 1499.0,
"price_history": [
{
"date": "2019-12-01",
"price": 1890.0
},
{
"date": "2019-12-02",
"price": 2000.0
}
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.