How to get executionStats using pymongo for an aggregate query?

317 views
Skip to first unread message

Bhavani Ravi

unread,
May 22, 2019, 5:34:58 AM5/22/19
to mongodb-user
res = db.command('aggregate', "CollectionName", pipeline=QUERY, explain=True)

this only returns operation time and cluster time

https://stackoverflow.com/questions/56253108/pymongo-aggregate-how-to-get-executionstats

Shane Harvey

unread,
May 23, 2019, 1:32:03 PM5/23/19
to mongodb-user
Your code returns the explain output for me using MongoDB 4.0:

>>> db = client.test
>>> QUERY = [{'$match': {'foo': 1}}]

>>> db.command('aggregate', "CollectionName", pipeline=QUERY, explain=True)
{'stages': [{'$cursor': {'query': {'foo': 1}, 'queryPlanner': {'plannerVersion': 1, 'namespace': 'test.CollectionName', 'indexFilterSet': False, 'parsedQuery': {'foo': {'$eq': 1}}, 'winningPlan': {'stage': 'COLLSCAN', 'filter': {'foo': {'$eq': 1}}, 'direction': 'forward'}, 'rejectedPlans': []}}}], 'ok': 1.0, 'operationTime': Timestamp(1558632270, 2), '$clusterTime': {'clusterTime': Timestamp(1558632270, 2), 'signature': {'hash': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 'keyId': 0}}}

For more detailed output  you can also use the explain command: https://docs.mongodb.com/manual/reference/command/explain/, like this:

>>> agg_cmd = SON([('aggregate', "CollectionName"), ('pipeline', QUERY), ('cursor', {})])
>>> db.command('explain', agg_cmd)
{'stages': [{'$cursor': {'query': {'foo': 1}, 'queryPlanner': {'plannerVersion': 1, 'namespace': 'test.CollectionName', 'indexFilterSet': False, 'parsedQuery': {'foo': {'$eq': 1}}, 'winningPlan': {'stage': 'COLLSCAN', 'filter': {'foo': {'$eq': 1}}, 'direction': 'forward'}, 'rejectedPlans': []}, 'executionStats': {'executionSuccess': True, 'nReturned': 1, 'executionTimeMillis': 0, 'totalKeysExamined': 0, 'totalDocsExamined': 1, 'executionStages': {'stage': 'COLLSCAN', 'filter': {'foo': {'$eq': 1}}, 'nReturned': 1, 'executionTimeMillisEstimate': 0, 'works': 3, 'advanced': 1, 'needTime': 1, 'needYield': 0, 'saveState': 1, 'restoreState': 1, 'isEOF': 1, 'invalidates': 0, 'direction': 'forward', 'docsExamined': 1}, 'allPlansExecution': []}}}], 'ok': 1.0, 'operationTime': Timestamp(1558632379, 1), '$clusterTime': {'clusterTime': Timestamp(1558632379, 1), 'signature': {'hash': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 'keyId': 0}}}

Best,
Shane
Reply all
Reply to author
Forward
0 new messages