0

So I am building a mongo database class that will be provide access to inserting documents to the insertion service and provide access for viewing documents via a querying service. Right now I have the following for my database.py class:

import pymongo 

client = pymongo.MongoClient('mongodb://localhost:27017/')
db_connection = client['my_database']

class DB_Object(object):

    """ A class providing structure and access to the Database """

    def add_document(self, json_obj):
        coll = db_connection["some collection"]
        document = {
            "name" : "imma name",
            "raw value" : 777,
            "converted value" : 333
        }
        coll.insert(document)

    def query_response(self, query):
            """query logic here"""

If I want concurrent queries and inserts with this class being called by multiple services is this the correct location for the lines:

client = pymongo.MongoClient('mongodb://localhost:27017/')
db_connection = client['my_database']

And is this a standard way to provide access?

1 Answer 1

1

Your code is correct. You should continue to use the same MongoClient instance for all operations in your application, this will ensure that all operations share the same connection pool and use as few connections as possible--this will maximize your efficiency. MongoClient is thread-safe so this will work even if you have concurrent operations on multiple threads.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.