3

I'm using Spring Data for Mongodb and sometimes I use the java driver this way :

DBCollection mycoll = mongoOperations.getCollection("mycoll");

Does it make sense to make the collection mycoll static and instantiate it through a Singleton?

Monta
  • 851
  • 1
  • 9
  • 21
  • You do not need a Singleton for this, you only need this design pattern if you can only ever have one instance at the same time and this is not the case for MongoDB collections. You should, however, use a singleton/static reference for the Mongo instance itself. – Alex Oct 22 '15 at 12:35
  • I'm asking this because in DEBUG mode I see "Getting Mongo database name [mycoll]" each time the previous line is traversed. So I said maybe it'd be better to do it once – Monta Oct 22 '15 at 12:44
  • Why is this line called multiple times ? I would typically expect it to be called once in the relevant data access class. – Alex Oct 22 '15 at 12:48
  • Imagine that it's written in a service method frequently called by the application. I thought it'd be better if the service method gets an existent reference rather than create it each time it's called – Monta Oct 22 '15 at 13:09

1 Answers1

3

You do not need a Singleton for this, you only need a Singleton if you can only ever have one instance and you need to manage that instance, see this post. The source code of the Java Mongo driver shows this is not the case for MongoDB collections. The 'getCollection` method only verifies if the collection exists in the collectionCache (a hashmap) and does not perform any database operations, so the overhead of calling it multiple times is minimal. See below the relevant code snippet from https://github.com/mongodb/mongo-java-driver

/**
 * Gets a collection with a given name.
 *
 * @param name the name of the collection to return
 * @return the collection
 */
public DBCollection getCollection(final String name) {
    DBCollection collection = collectionCache.get(name);
    if (collection != null) {
        return collection;
    }
Community
  • 1
  • 1
Alex
  • 19,061
  • 10
  • 50
  • 66