![]() ![]() You can see the collections in the MongoDB Compass UI as well. Upon executing the above code, a new collection with name User will get created in our database. Working on a local database is part of developing any web, desktop, or mobile application. This is the default port the MongoDB database server listens to the commands. ("Collection User created successfully") To connect your application with your local MongoDB database, you need to connect MongoDB on the localhost 27017 port. MongoEngine provides connect() function to connect to a running instance. If we want to create a collection(just like table in relational DB) from our java program, we can do so like this: package com.mongo ĭb.createCollection("User", new BasicDBObject()) As mentioned earlier, you should first start MongoDB server using mongod command. The above java code which is used to display list of all the databases is similar to the MySQL command show databases MongoDB: Create a Collection MongoClient.getDatabaseNames().forEach(System.out::println) Once we are able to successfully establish connection using MongoClient, we can use the following code to display all the databases available: // display all the databases If your MongoDB is running in authenticated mode, then you will have to provide the username and password while connecting to the database, like this: // code to connect to the database with authenticationīoolean auth = db.authenticate("username", "password".toCharArray()) Mongo mongo = new Mongo("localhost", 27017) NOTE: If you are using an older version of the mongodb java driver which is <= 2.10.0, then you should use the following code with Mongo class to create the connection. When the above mentioned code is executed, following output will be produced on console: ("Database DemoDB connected successfully") ![]() MongoClient mongoClient = new MongoClient("localhost", 27017) Step 1 Download Node. To find the latest version of the above Mongo Java driver, check the following link.īelow we have a simple Java class with a main() method which uses the MongoClient class to setup connection with MongoDB. So we will be adding Maven dependency like this: Java Code to Make Connection with MongoDBįirst we must add the mongo-java-driver-3.10.0.jar file as a dependency in our Java project. We can connect to the DB using this user interface and then test our queries here. Here, we are making use of MongoDB Compass - a GUI tool for MongoDB for visualizing our query output. Now, we are ready for performing CRUD operations with MongoDB through Java. In this, we will learn how to integrate MongoDB with Java and will explore the basic CRUD (Create, Retrieve, Update and Delete) operations.ĭownload Jar, use mongo-java-driver-3.10.0.jar. ![]()
0 Comments
Leave a Reply. |