[英]Pymongo Not inserting full document on update_one
我有很多文档要更新,我想先写一个时间戳,然后在有重复时写一个更新时间戳。 所以我找到了这个答案,并正在尝试为 MongoDB 6.0 https://stackoverflow.com/a/17533368/3300927
我还将查找重复项时使用的变量存储在searchable
中
如果查询没有searchable
的,那么我在不检查的情况下插入它并添加时间戳,然后获取结果并添加时间戳:
data_inserted = collection.insert_many(results)
for doc_id in data_inserted.inserted_ids:
collection.update_many(
filter={'_id': doc_id},
update={'$set': {'insert_date': now, }, },
upsert=True)
那里没有问题:
{
"_id": {
"$oid": "321654987654"
},
"IR NUMBER": "ABC784",
"Plate": " ",
"Plate State": " ",
"Make": "TOYOTA",
"Model": "TACOMA",
"Style": " ",
"Color": "SIL / ",
"Year": "2008",
"insert_date": {
"$date": {
"$numberLong": "1660000808176"
}
}
}
如果有searchable
的,我会尝试寻找它。 我在 MongoDB 中得到的只是带有时间戳的searchable
字段:
# q_statement.searchable == 'IR NUMBER'
for document in results:
collection.update_one(
filter={q_statement.searchable: document[q_statement.searchable], },
update={'$setOnInsert': {'insert_date': now, }, '$set': {'update_date': now, }},
upsert=True)
结果:
{
"_id": {
"$oid": "62f19d981aa321654987"
},
"IR NUMBER": "ABC784",
"insert_date": {
"$date": {
"$numberLong": "1660001688126"
}
}
}
编辑
通过将for
循环内容更改为更新来查看pymongo.results.UpdateResult
updates = collection.update_one(... print(updates.raw_result)
显示约 10k 个结果,例如:
{
"n": 1,
"upserted": ObjectId("62f27ae21aa62fbfa734f01d"),
"nModified": 0,
"ok": 1.0,
"updatedExisting": False
},
{
"n": 1,
"nModified": 0,
"ok": 1.0,
"updatedExisting": True
},
{
"n": 1,
"nModified": 0,
"ok": 1.0,
"updatedExisting": True
}
(python==3.10.3,Django==4.0.4,pymongo==4.2.0)
要使用python
"upsert"
完整文档和其他字段,您可以将 MongoDB 的"$setOnInsert"
与python
合并字典一起使用。
来自python 库文档,这里是合并字典的方法。 (它类似于 MongoDB 的"$mergeObjects"
。)
d | other
Create a new dictionary with the merged keys and values of d and other,
which must both be dictionaries. The values of other take priority
when d and other share keys.
因此,要插入完整的document
,使用您的 python 代码,它只需要一个小的添加 - 与您的其他 object 合并document
。
...
update={'$setOnInsert': document | {'insert_date': now}, '$set': {'update_date': now, }}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.