Forum Discussion

SriAchar's avatar
SriAchar
Occasional Contributor
8 years ago

Connection to MongoDB

Hi All,

 

I am trying to connect to MongoDB using Groovy. Here is what I have tried:

 

import com.gmongo.GMongo

def mongo = new GMongo("<server_name>:<port>")

def db = mongo.getDB("<DB_Name>")

def collection = db.getCollection("<Collection_Name>")

log.info collection.findOne(<Key1>:<Value1>).<Key2>

 

I am getting the value associated with Key2. However, this DB is installed in one of local machine and doesn't have authentication involved. The challenge I am facing is to connect to the DB (in cloud), which has authentication involved in it.

 

Can someone guide me?

    • SriAchar's avatar
      SriAchar
      Occasional Contributor

      Hi Rupert,

       

      As in your example, I am using this:

       

      import com.gmongo.*
      import com.mongodb.*
      import com.gmongo.GMongo
      import com.mongodb.MongoCredential

       

      def credential = MongoCredential.createMongoCRCredential("<username>", "<database>","<password>".toCharArray())
      log.info "credential excepted"
      log.info credential

       

      def client = new MongoClient(new ServerAddress("<server address>",port), [credential])
      log.info "client excepted"
      log.info client

       

      def mongo = new GMongo (client)
      log.info "mongo excepted"
      log.info mongo

       

      def db = mongo.getDB("<database>")
      log.info "db excepted"
      log.info db

       

      def collection = db.getCollection("<collection>")
      log.info "collection excepted"
      log.info collection

       

      log.info collection.findOne(<key1>:"<value1>").<key2>

       

      I am getting the error: ERROR:com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=<address>, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketReadTimeoutException: Timeout while receiving message}, caused by {java.net.SocketTimeoutException: Read timed out}}].

       

      Using the log.info, I am getting the logs till "collection expected" and collection info. Hence, I am assuming, it connected but was not able to execute the last line.

       

      Also, in your example, the first line is:

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

      I am not sure how to use this. Putting that in my script, the error comes up:

      java.lang.NoClassDefFoundError: org/apache/ivy/core/settings/IvySettings

      Thanks,

      Srikanth