Using maxTimeMS parameter with aggregation queries on Mongo 2.6 and Pymongo 2.7.1

一曲冷凌霜 提交于 2019-12-20 04:53:38

问题


  • I'm unable to use maxTimeMS parameter with Mongo 2.6 and Pymongo 2.7.1

  • As per the documentation on this page Official Mongodb Aggregation Page the aggregation method should return a Cursor object. However, when I run the query locally on a mongod instance (2.6+) with pymongo 2.7.1, I get a dict object!

In [14]: obj = coll.aggregate({'$group': {'_id': '$l', 'n': {'$sum': 1}}})

In [15]: type(obj) Out[15]: dict

Can anyone help me understand what is happening here?


回答1:


Yes, you can use maxTimeMS with pymongo aggregation.

c.foo.bar.aggregate([], maxTimeMS=1000)
{u'ok': 1.0, u'result': []}

If you want a cursor:

for result in c.foo.bar.aggregate([], cursor={}, maxTimeMS=1000):
... print result

The aggregate command didn't support cursors before MongoDB 2.6 so it had to be added as an option to avoid breaking existing applications.




回答2:


This is covered in the driver documentation where it is described that in order to return a cursor, you need to specify the arguments in addition to the pipeline in your .aggregate() method:

cursor = coll.aggregate([{'$group': { '_id': '$l', 'n': {'$sum': 1} }}],cursor={})

Note that the returned object here is a CommandCursor and not a cursor.

This is because various modifiers such as .limit() and .skip() and other options do not apply in the context of an aggregation result. As such $maxTimeMS is not a valid option for this type of cursor.

In addition, it would not do what you think it will even where valid. The reason being that the "cursor" execution is only counted "after" the "aggregation pipeline" execution is complete, so in this case, just fetching the results.

Look at the .currentOp() and .killOp() implementations for other ways to control long running aggregation tasks.



来源:https://stackoverflow.com/questions/24691093/using-maxtimems-parameter-with-aggregation-queries-on-mongo-2-6-and-pymongo-2-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!