问题 一: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