Forum Discussion

SriAchar's avatar
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>") 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?

11 Replies

    • SriAchar's avatar
      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()) "credential excepted" credential


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


      def mongo = new GMongo (client) "mongo excepted" mongo


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


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



      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 { Read timed out}}].


      Using the, 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