I spent years trying to find a simple example where MongoEngine was used and the connection was closed. Finally figured it out and posted my code.
1 > malla..:
I thought disconnect()
should have been used originally, but it has been removed as a synonym for close()
.
from mongoengine import connect def main(): #connect to db db_client = connect('my_db', host='localhost', port=27017) #close the connection db_client.close() if __name__ == "__main__": main()
2> Ash..:
I know this is an old question, but if anyone is searching, I thought I would give an alternative answer.
close()
does not actually delete the connection from MongoEngine’s connection list. This can cause problems when trying to connect to other databases later.
To solve this problem, I used mongoengine.connection.disconnect
(even though __all__
was not listed). My code looks like this:
from mongoengine import connect from mongoengine.connection import disconnect db = connect(alias='some_alias') {do stuff} disconnect(alias='some_alias')
You can also omit the alias as it will default to “default” on connects and disconnects.