[英]pymongo update not working
我正在嘗試使用pymongo更新mongoDB中的一行。 它似乎一切正常,除了它實際上沒有更新行! 有什么我想念的東西(例如沖洗命令嗎?)。 以下代碼段:
In [161]: articles = connection.journals.articles.find()
In [162]: articles[0]['_id']
Out[162]: ObjectId('4ee61fc0df04c08c5c510b51')
In [163]: articles[0]['newfield'] = 'Test'
In [164]: connection.journals.articles.update({'_id': articles[0]['_id']}, articles[0], safe=True)
Out[164]:
{u'connectionId': 62,
u'err': None,
u'n': 1,
u'ok': 1.0,
u'updatedExisting': True}
In [165]: articles = connection.journals.articles.find()
In [166]: articles[0]['_id']
Out[166]: ObjectId('4ee61fc0df04c08c5c510b51')
In [167]: articles[0]['newfield']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
script.py in <module>()
----> 1
2
3
4
5
KeyError: 'newfield'
這里有一些代碼可以幫助您了解正在發生的事情:
# make a connection
>>> import pymongo
>>> articles = pymongo.Connection()['test']['articles']
# insert an article and print out it's contents (make sure it's there)
>>> articles.insert({"title": "tyler's article"})
>>> article = articles.find_one()
>>> article
{u'_id': ObjectId('4f0b353c096f762312000002'), u'title': u"tyler's article"}
# update the title to something new
>>> article['title'] = "test"
# save it
>>> articles.save(article)
# check to see if it changed
>>> print articles.find_one()
{u'_id': ObjectId('4f0b353c096f762312000002'), u'title': u'test'}
作為find()
調用的結果, PyMongo Cursor實際上不是一個列表,它只是實現__getitem__
來模擬類似列表的訪問。 實際上,每次使用項目訪問表示法時,它都會對數據庫執行新的查詢,並設置適當的skip()
和limit()
以返回您要查找的項目。 因此,正如您在評論中所懷疑的那樣,修改articles[0]
的結果將不起作用,但是引用articles[0]
的結果,然后在update()
修改和使用它將起作用。
您還應該知道在某些情況下(基本上,如果修改導致文檔增長超出可用的“下一個”可用空間),文檔可能會被MongoDB在磁盤/內存中移動。 由於您未在find()
調用中使用sort()
,因此您將以未定義的順序獲得結果。 當文檔移動時,如果文檔已移動,則find()
調用中結果的順序可能會更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.