[据说这么起标题,更容易拉来访问量…]

motor是tornado对MongoDB的异步的库, 0.5版本之前使用聚集操作时,可以直接使用yield关键字,像这样,cols = yield db.col.aggregate([{..}, {..}]), 但升级库到0.5之后,将会报yielded unknown object MotorAggregationCursor的错误 解决方式直接看代码吧

  ~ ~/py35env/bin/python
Python 3.5.1 (default, Dec 30 2015, 23:37:24)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import motor
>>> youcai = motor.MotorClient('127.0.0.1:27017').youcai
>>> from tornado.gen import coroutine
>>> from tornado.ioloop import IOLoop
>>> @coroutine
... def wrong_way():
...   cols = yield youcai.col.aggregate([{'$match': {'point': 65}}, {'$group': {'_id': '$age'}}])
...   return cols
...

>>> @coroutine
... def correct_way():
...   cols = []
...   ret = youcai.col.aggregate([{'$match': {'point': 65}}, {'$group': {'_id': '$age'}}])
...   while(yield ret.fetch_next):
...     doc = ret.next_object()
...     cols.append(doc)
...   return cols
...

>>> IOLoop.current().run_sync(wrong_way)  #保错 yielded unknown object MotorAggregationCursor
>>> IOLoop.current().run_sync(correct_way)
[{'_id': 17}, {'_id': 14}]     # 正确姿势, 获得结果
>>>