我有一个需要更新的Mongo Collection,而且我试图使用collection.update命令无效。
以下代码:
import pymongo
from pymongo import MongoClient
client = MongoClient()
db = client.SensorDB
sensors = db.Sensor
for sensor in sensors.find():
lat = sensor['location']['latitude']
lng = sensor['location']['longitude']
sensor['location'] = {
"type" : "Feature",
"geometry" : {
"type" : "Point",
"coordinates" : [lat ,lng]
},
"properties": {
"name": sensor['name']
}
}
sensors.update({'webid': sensor['webid']} , {"$set": sensor}, upsert=True)
然而,运行它会得到以下结果:
Traceback (most recent call last):
File "purgeDB.py", line 21, in <module>
cameras.update({'webid': sensor['webid']} , {"$set": sensor}, upsert=True)
File "C:\Anaconda\lib\site-packages\pymongo\collection.py", line 561, in update
check_keys, self.uuid_subtype), safe)
File "C:\Anaconda\lib\site-packages\pymongo\mongo_client.py", line 1118, in _send_message
rv = self.__check_response_to_last_error(response, command)
File "C:\Anaconda\lib\site-packages\pymongo\mongo_client.py", line 1060, in __check_response_to_last_error
raise OperationFailure(details["err"], code, result)
pymongo.errors.OperationFailure: Mod on _id not allowed
答案 0 :(得分:4)
更改此行:
for sensor in sensors.find():
到此:
for sensor in sensors.find({}, {'_id': 0}):
这样做可以防止Mongo返回_id
字段,因为您没有使用它,并且由于您无法“更新”{{1,因此导致您在update()
调用中出现问题}}
更好的解决方案(只写下需要的数据)
_id
修改强>
正如LoïcFaure-Lacroix所提到的,在你的情况下你也不需要for sensor in sensors.find():
lat = sensor['location']['latitude']
lng = sensor['location']['longitude']
location = {
"type" : "Feature",
"geometry" : {
"type" : "Point",
"coordinates" : [lat ,lng]
},
"properties": {
"name": sensor['name']
}
}
sensors.update({'webid': sensor['webid']} , {"$set": {'location': location}})
标志 - 在这种情况下你的代码总是在更新,而且永远不会插入。
<强> EDIT2:强>
在第一个解决方案的引号中包围upsert
。