如果键不存在,我想向集合中添加一条记录。我了解 [MongoDB][1] 为此提供了 upsert
,所以我做了一个
db.collection.update({"_id":"key1"},{"_id":"key1"},True)
这似乎有效。
然而在 Pymongo documentation它说更新已被弃用并用于 update_one()
。
但是:
db.collection.update_one({"_id":"key1"},{"_id":"key1"},True)
给予:
raise ValueError('update only works with $ operators')
ValueError: update only works with $ operators
我真的不明白为什么 update_one
不同以及为什么我需要使用 $
运算符。有人可以帮忙吗?
最佳答案
这是因为您没有指定任何 update operator .
例如到 $set
id
值使用:
db.collection.update_one({"_id":"key1"}, {"$set": {"id":"key1"}}, upsert=True)
请注意,在 Mongo shell 中,这只会用新文档替换文档。
https://stackoverflow.com/questions/30605638/