Oct 10, 2018

[HDGEM] MongoDB Java connection Example

<dependency>              <groupId>org.mongodb</groupId>              <artifactId>mongodb-driver</artifactId>              <version>3.4.2</version>              <type>jar</type>  </dependency>
  
public static void main(String[] args) {          MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://my-document-db-name:[email protected]:10250/?ssl=true&sslInvalidHostNameAllowed=true"));          MongoDatabase turnstyle = mongoClient.getDatabase("turnstyle");          MongoIterable<String> collectionNames = turnstyle.listCollectionNames();                        turnstyle.createCollection("test");                    collectionNames = turnstyle.listCollectionNames();                    for(String name: collectionNames) {              System.out.println(name);          }                        }

Once we get the connection to MongoDB server, next step is to create the connection to the database, as shown below. Note that if database is not present, MongoDB will create it for you.
MongoDatabase turnstyle = mongoClient.getDatabase("turnstyle");

MongoClient provide a useful method to get all the database names, as shown below.
        MongoIterable<String> databaseNames = mongoClient.listDatabaseNames();          for(String name: databaseNames) {              System.out.println(name);          }

MongoDB and Collections


Every database can have zero or multiple collections, they are like tables in relational database servers except that you don't have specific format of data. Think of it like a generic list vs list of Strings in terms of java programming language.

        MongoIterable<String> collectionNames = turnstyle.listCollectionNames();                        turnstyle.createCollection("test");                    collectionNames = turnstyle.listCollectionNames();                    for(String name: collectionNames) {              System.out.println(name);          }


--
Posted By Blogger to HDGEM at 3/20/2017 01:54:00 PM