Reputation: 277
I am new to Mongo, and was wondering what best practices would be in terms of accessing collections. Best way to explain is through sudo code:
public class DBManager {
private MongoClient mongoClient;
private DBCollection collection;
public DBManager() {
mongoClient = new MongoClient( "127.0.0.1", 27017);
collection = mongoClient.getDB( "DB" ).getCollection("collection");
}
public String add(String item) {
if(collection!= null) {
ObjectId id = new ObjectId();
BasicDBObject insert= new BasicDBObject("_id", id)
.append("item", item)
collection.insert(insertRepo);
return id.toHexString();
}
return null;
}
public boolean remove(String id) {
if(collection!= null) {
ObjectId id = new ObjectId(id);
DBObject dbObject = collection.findOne(objectId);
collection.remove(dbObject);
}
return false;
}
}
I'm not really clear on what happens behind the scenes when you do "getCollection". Is it good practice to just do it once when you initialize, or should i be just setting up the MongoClient in the constructor and then getting the collection for each request?
Upvotes: 1
Views: 1054
Reputation: 20699
it's fine to do it in the constructor. It's even better to define the DBManager
as a singleton
, so that the collection is initialized during boot-strap
Upvotes: 1