關於pymongo的一些說明

問題 一:shell

在pymongo中使用find是獲得1個遊標對象的,若是你想實現MongoDB shell中find操做,例如:數據庫

> db.test.find()
{ "_id" : ObjectId("5838531e0f3577fc9178b834"), "name" : "zhangsan" }

在pymongo中須要使用find_one方法而不是find方法:app

>>> print db.test.find_one()
{u'_id': ObjectId('5838531e0f3577fc9178b834'), u'name': u'zhangsan'}

>>> print db.test.find()
<pymongo.cursor.Cursor at 0x7f4ac789e450>
>>> result = []
>>> for x in db.test.find():
          result.append(x)
>>> print(result)
>>> [{u'_id': ObjectId('5838531e0f3577fc9178b834'), u'name': u'zhangsan'},...]

 

  因此在pymongo中,若是判斷一條數據是否存在。這樣寫是錯誤的。由於find返回的是遊標,條件判斷永遠成立。spa

        if self.db[self.ids_seen].find(data):
            raise DropItem("Duplicate item found: %s" %item['title'])

  正確的寫法是這樣的。code

 if self.db[self.ids_seen].find_one(data):
            raise DropItem("Duplicate item found: %s" %item['title'])

 

問題 二:對象

  self.db 取到數據庫。blog

  self.db 能夠直接中括號表示 數據庫中的表。 self.db [ ' username' ] . find_one( { 'name':'sb' } )it

相關文章
相關標籤/搜索