Experiment No-08
Title :- Accessing MongoDB from some of the popular
high-level programming languages. Perform Create, Retrieve, Update and Delete
or CRUD operations in MongoDB.
Aim : To implement Java-MongoDB Connectivity
Theory: MongoDB comes with its own non-JDBC driver
called Mongo Java Driver.
import java.net.UnknownHostException;
import java.util.List;
import java.util.Set;
import com.mongodb.DB;
import com.mongodb.MongoClient;
public class JavaMongoDBConnection {
public static void main(String[] args) {
try {
MongoClient mongoClient = new
MongoClient("localhost");
List<String> databases =
mongoClient.getDatabaseNames();
for (String dbName : databases) {
System.out.println("- Database: " +
dbName);
DB db = mongoClient.getDB(dbName);
Set<String> collections =
db.getCollectionNames();
for (String colName : collections) {
System.out.println("\t + Collection: " +
colName);
}
}
mongoClient.close();
} catch (UnknownHostException ex) {
ex.printStackTrace();
}
}
}
This Java program connects to a MongoDB server
running on localhost at default port, then lists all database names available on
the server. For each database, it lists all collection names (a collection is
equivalent to a table in relational database), and finally closes the
connection.
Conclusion: Students are able to access documents
from Mongodb using JAVA.