Search This Blog

Sunday 15 June 2014

Talking to MongoDB via java

In our last post we got started on creating a database and adding docs to a collection. Being a java guy, I wanted to try and use the database connectivity driver provided by MongoDB for use with java applications.
Accordingly I created a sample application and added the mongo-java-driver-2.9.3.jar from the website. The sample code is as below:
   public static String DB_NAME = "fruits";
   public static String COLLECTION_NAME = "fruits";

   public static void main(String[] args) throws UnknownHostException {
      // A database connection with internal connection pooling. For most
      // applications, you should have one Mongo instance
      // for the entire JVM.
      // To directly connect to a single MongoDB server
      Mongo mongoClient = new Mongo();
      System.out.println("MaxBsonObjectSize : "
            + mongoClient.getMaxBsonObjectSize());
      System.out.println("Connect Point : " + mongoClient.getConnectPoint());
      System.out.println("Options : " + mongoClient.getOptions());
      System.out.println("Version : " + mongoClient.getVersion());
      System.out.println("Major Version : " + Mongo.getMajorVersion());
      System.out.println("Minor Version : " + Mongo.getMinorVersion());
      List<String> dbNames = mongoClient.getDatabaseNames();
      System.out.println("Database names are ");
      for (String dbName : dbNames) {
         System.out.print(" " + dbName);
      }

      DB targetDB = mongoClient.getDB(DB_NAME);
      Set<String> collections = targetDB.getCollectionNames();

      System.out.println("\nCollections in " + targetDB.getName() + " are ");
      for (String collection : collections) {
         System.out.print(collection + " ");
      }

      mongoClient.close();
   }
The code:
  • Gets a connection to the MongoDB server.
  • It displays database server information.
  • It connects to the selected database and displays the names of available collections.
  • It finally closes the connecton.
On running the code:
MaxBsonObjectSize : 16777216
Connect Point : /127.0.0.1:27017
Options : 0
Version : 2.9.3
Major Version : 2
Minor Version : 9
Database names are 
 fruits local
Collections in fruits are 
fruits random system.indexes
The code displays the MongoDB version. It shows the databases - local and the one I created in the previous execution.
The next step would be to actually read and write documents.

No comments:

Post a Comment