[ACCEPTED]-Do I need to close connection in mongodb?-pymongo

Accepted answer
Score: 14

There's no need to close a Connection instance, it 13 will clean up after itself when Python garbage 12 collects it.

You should use MongoClient instead of Connection; Connection is 11 deprecated. To take advantage of connection 10 pooling, you could create one MongoClient that lasts 9 for the entire life of your process.

PyMongo 8 represents documents as dicts. Why are you 7 encoding each dict it gives you as JSON, then 6 decoding it again? It may be more efficient 5 to modify the objects directly.

That 4 said, I agree with user3683180 that the 3 real problem--the reason MongoDB is taking 2 so much CPU--is in your schema or index 1 design, not in your Python code.

Score: 8

Given the name of your database 'indexer', and 7 the 'unique' property which requires an 6 index, I'm thinking your CPU usage might 5 have nothing to do with this code.

Try using 4 mongostat and mongotop to see what mongo 3 is spending its time doing.. I'm thinking 2 you'll find it's spending time crunching 1 data and that your code is just fine.

More Related questions