refactor pymongo code in python file