Forum Discussion

elenal's avatar
elenal
Occasional Contributor
8 years ago

how to close mongodb connection

I have a script that fetches data from mongodb

@Grab(group='com.gmongo', module='gmongo', version='1.5')

import com.gmongo.GMongo
import com.mongodb.MongoCredential
import com.mongodb.*
import com.mongodb.ServerAddress
import com.gmongo.*
import com.mongodb.MongoURI
import com.mongodb.DBCursor;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBList
import org.bson.types.ObjectId

//define variables from mongo document
def mongo_name
def mongo_description
def mongo_type


//define mongo_variables and initiate mongo connection
def mongoendpoint = context.expand( '${#Project#mongoendpoint}' )
def mongocollection=context.expand( '${#Project#mongocollection_products}' )
def mongo= new GMongo (new MongoURI(mongoendpoint))
def db = mongo.getDB(mongocollection)
def collection = db.getCollection("ProductItems")

//define elements from API response
def api_productId = context.expand('${#Project#package_parent}')

//get document from mongo
DBCursor cursor=collection.find(_id : api_productId)
//log.info cursor

if (cursor.hasNext() )
{ DBObject obj = cursor.next()
//mongo_name=obj.name.toString()
}

 //close cursor
cursor.close()

My problem is that connection stays open until I shut down ReadyAPI which leads to too many open (and not closed) connections.

 

Is it anyway to explicitly close connection? (googled, but couldn't find a solution which would work)