PyMongo Aggregation not working

With the announcement of PyMongo being the preferred driver over Motor, I looked at my current FastAPI deployment and what it would take to move over. 90% of the code moved with no issues, but I have a couple of endpoints using .aggregate() method with pipelines built to combine data from 2 collections into 1 output.

I’m getting an error of “async for requires an object with aiter method, got coroutine”.

Does anyone know if this is being worked on? or is there something I’m not seeing with aggregate that PyMongo does differently than Motor?

1 Like

Hello!
Without knowing exactly what your code looks like, I’m guessing you have a line like async for document in collection.aggregate(pipeline): that is causing the error.
If that is the case, I believe that adding an await prior to the aggregate call would resolve your issue. So the previously stated line would be: async for document in await collection.aggregate(pipeline):

If this doesn’t solve your problem, would you post a snippet of your code that produces the error?

2 Likes

You were more or less correct on the code. I will do more testing tonight and tomorrow, but this appears to work in my quick test!

1 Like