sarah w
sarah w

Reputation: 3475

when do we need to close MongoConnection

I am using mongo cashbash here is my code

case class A (id:String,name:String)

class InsertClassA(a:A) 
{
   def inserA()={
   val mongoClient=MongoClient(hostName,port)
   //get collection and insert record in mongo
   mongoClient.close()
   }
}

class UpdateClassA(a:A) 
{
   def UpdateA()={
   val mongoClient=MongoClient(hostName,port)
   //get collection and update record in mongo
   mongoClient.close()
   }
}

class DeleteClassA(a:A) 
{
   def deleteA()={
   val mongoClient=MongoClient(hostName,port)
   //get collection and delete record in mongo
   mongoClient.close()
   }
}

object test extends App {
 val a =A("123","bob")
 val insert =new InsertClassA(a)
 val update =new UpdateClassA(a)
 val delete =new DeleteClassA(a)

 insert.insertA()
 update.UpdateA()
 delete.deleteA()
}

I want to know when should i close a mongoConnection? The above approach is correct ? if not what is the right way to not waste any resources and utilize the mongoCLient instance in well manner ,please guide me

Upvotes: 1

Views: 68

Answers (1)

mtj
mtj

Reputation: 3554

Generally, the MongoClient is a heavyweight component tailored for long lifetime (i.e. application lifetime.) Thus, you should rather open it once in the beginning and retain the reference.

Upvotes: 3

Related Questions