Explain on aggregate function with python pymongo

I am trying to explain but it seems i do something wrong.
My query:

#   [
#       {
#         "$match": {
#            "timestamp1": {"$gte": datetime.strptime("2020-01-01 00:05:00", "%Y-%m-%d %H:%M:%S"),
#                           "$lte" :datetime.strptime("2020-01-01 01:05:00", "%Y-%m-%d %H:%M:%S")}
#         }
#       },
#       {
#         "$group": {
#
#           "_id": {"$dateToString": { "format": "%Y-%m-%d %H", "date": "$timestamp1" }},
#           "max_id13": {
#             "$max": "$id13"
#           }
#         }
#       },
#
#      {
#         "$project": {
#             "_id":0,
#             "day":"$_id",
#             "max_id13":1
#          }
#      },
#       {"$sort": {"day": 1}}
#     ]
# ).explain()['executionStats'])

Output: AttributeError: 'CommandCursor' object has no attribute 'explain'
Any help?Thanks in advance!

Hello @harris,

The explain method on the aggregation pipeline can be used as follows. Note that the command collection.aggregate doesn’t support the explain in PyMongo - you need to use the db.command syntax as shown in the example.

agg_pipeline = [
    {
        "$match": {
            "timestamp1": {"$gte": datetime.strptime("2020-01-01 00:05:00", "%Y-%m-%d %H:%M:%S"),
                           "$lte" :datetime.strptime("2020-01-01 01:05:00", "%Y-%m-%d %H:%M:%S")}
        }
    },
    {
        "$group": {
           "_id": {"$dateToString": { "format": "%Y-%m-%d %H", "date": "$timestamp1" }},
           "max_id13": {
             "$max": "$id13"
           }
        }
    },
    {
        "$project": {
            "_id":0,
            "day":"$_id",
            "max_id13":1
        }
    },
    { "$sort": {"day": 1} }
]

explain_output = db.command('aggregate', 'collection_name', pipeline=agg_pipeline, explain=True)

pprint.pprint(explain_output)
4 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.