关于pymongo的一些说明

问题 一:

在pymongo中使用find是得到1个游标对象的,如果你想实现MongoDB shell中find操作,例如:

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

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

>>> 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返回的是游标,条件判断永远成立。

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

  正确的写法是这样的。

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

问题 二:

  self.db 取到数据库。

  self.db 可以直接中括号表示 数据库中的表。 self.db [ ' username' ] . find_one( { 'name':'sb' } )

猜你喜欢

转载自www.cnblogs.com/654321cc/p/9077829.html
今日推荐