我目前正在嘗試編寫一個拼圖網站的MongoDB後端。我對pymongo相當陌生,我一直在努力尋找一種方法來檢查唯一的密鑰標識符,並在子文檔退出時更新它。我的佈局是這樣的:檢查_id是否存在使用和更新子文檔Pymongo
{
_id : Jack
"username": Jack
"puzzles": [
{
"name": puzName,
"rank": rank,
"date": puzDate,
"Global Score": score,
"Points": points
}
],
"attempts": 1
}
如果傑克已經存在,我想它這樣做:
{
_id : Jack
"username": Jack
"puzzles": [
{
"name": puzName,
"rank": rank,
"date": puzDate,
"Global Score": score,
"Points": points
}
{
"name": puzName2,
"rank": rank,
"date": puzDate,
"Global Score": score,
"Points": points
}
],
"attempts": 2
}
要填充字段,我是從現有的HTML和使用美麗的湯服用領域。
cells = row('td')
rank = cells[0].string
name = cells[1].find_all('a')[1].find(text=True).strip()
score = row('td')[3].string
points = row('td')[4].string
puz_dict = {}
puz_dict['_id'] = name.encode('ascii','ignore')
puz_dict['username'] = name.encode('ascii','ignore')
puz_dict['puzzles'] = {'Puzzle Name': puzName, 'Rank': int(str(rank)), "Date": puzDate,'Global Score' : locale.atoi(str(score)), 'Points' : int(str(points)) }
puz_dict['attempts'] = 1
connection = MongoClient('localhost')
coll = connection['Puzzles']['Users']
if col.find({'_id' : puz_dict['_id']}).count() > 0:
Print "Updating User"
update stuff
else:
coll.insert(puz_dict)
正如您所見,我使用用戶名作爲唯一標識文檔的方式。到現在爲止還挺好。檢查數據庫,用戶信息正確填充。
現在我想檢查用戶是否已經存在,如果他們這樣做,更新「拼圖」字段以包含該拼圖並將更新增加1.我認爲這可以檢查存在,但它似乎並沒有工作,而是直接插入:
if col.find({'_id' : puz_dict['_id']}).count() > 0:
Print "Updating User"
update stuff
爲什麼它沒有正確檢查?我如何更新子文檔?
而如果「用戶」不存在?如何使用['update_one()'](https://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one)方法? – styvane
所以如果用戶(_id)不存在於集合中,那麼計數應該是0.如果它是0,那麼else中的insert()將被執行。這將在集合中創建一個新的_id和用戶。我沒有包含我的更新代碼,因爲我沒有測試過它。我想讓find()正常工作首先更重要 – jaybeatle
您的find()查詢是否返回任何文檔?你也有一個錯字。你正在使用'col.find()'而不是'coll.find()',也許這是罪魁禍首。但坦率地說,你不需要使用'coll.find()。count()''你可以使用'update_one()'方法並將'upsert'選項設置爲'True',然後檢查'upserted_id'的值和'modified_count'並相應地打印一條消息。 – styvane