![](/img/trans.png)
[英]Update new document field value based on match of previous records in MongoDB collection
[英]How to update a field in MongoDB with new value
我正在嘗試瀏覽集合中的記錄,其中坐標字段中沒有經度/緯度信息。 使用Google的geocode()
方法,我選擇具有位置信息的記錄,以轉換為坐標,然后更新coordinates
字段中的新值,該值以前為null
。
使用find()
方法,我正在獲取相關的記錄,但是此代碼塊似乎並未執行,即,記錄未使用坐標信息進行更新。 這是代碼:
cursor = coll.find(
{"$and": [
{"coordinates": {"$type":10}},
{"place": {"$ne": None}}
]},
{"coordinates": 1, "place": 1, "time_normal": 1, "_id": 1}, tailable = True, timeout = False)
while cursor.alive:
counter=0
g = geocoders.Google()
try:
doc = cursor.next()
current_id = doc['_id']
counter+=1
print doc
placeName = doc['place']['full_name']
loc = g.geocode(placeName)
coll.update({"_id" : current_id},{"$set": {"coordinates": loc[1]}})
print doc
time.sleep(0.15)
except (ValueError, geocoders.google.GQueryError):
pass
except StopIteration:
break
我看不到為什么未更新該字段。 我注意到print counter
返回0。
謝謝
幾件事情:
您可以稍微簡化find
查詢以刪除$and
因為在查詢選擇器中包括多個字段自然會將它們“和”起來:
cursor = coll.find(
{
{"coordinates": {"$type":10}},
{"place": {"$ne": None}}
},
{"coordinates": 1, "place": 1, "time_normal": 1, "_id": 1},
tailable = True, timeout = False)
但這不應該引起任何問題,您的update
調用看起來不錯。 但是,不要期望doc
會被update
調用修改,因為它是find
調用時文檔外觀的快照。 您需要在此時調用find_one({"_id": current_id})
才能查看更新結果。
如果看起來仍然沒有更新,請在更新之前查看loc[1]
的內容,以確保它符合您的期望。
更新
問題可能出在您試圖更新一個有上限的集合而導致文檔大小增加的問題。 根據docs ,這將導致更新失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.