Environment configuration
If you want to use MongoDB in a Java program, you need to ensure that the Java environment and the MongoDB JDBC driver have been installed.
You can refer to the Java tutorial on this site to install the Java program. Now let’s check if you have the MongoDB JDBC driver installed.
First you have to download mongo
jar package, download address: https://github.com/mongodb/mongo-java-driver/downloads,
Make sure to download the latest version.
You need to include mongo.jar in your classpath. .
Connect to database
To connect to the database, you need to specify the database name. If the specified database does not exist, mongo will automatically create the database.
Java to connect to the database
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// Connect to mongodb service
MongoClient mongoClient = new MongoClient( “localhost”, 27017 );
// Connect to database
DB db = mongoClient.getDB( “test” );
System.out.println(“Connect to database successfully”);
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println(“Authentication: “+auth);
}catch(Exception e){
System.err.println( e.getClass().getName() + “: ” + e.getMessage() );
}
}
}
Now, let’s compile and run the program and create the database test.
You can change the path of the MongoDB JDBC driver according to your actual environment.
In this example, the MongoDB JDBC startup package mongo-2.10.1.jar is placed in the local directory:
$javac MongoDBJDBC.java
$java -classpath “.:mongo-2.10.1.jar” MongoDBJDBC
Connect to database successfully
Authentication: true
If you are using a Windows system, you can compile and execute the program with the following command:
$javac MongoDBJDBC.java
$java -classpath “.;mongo-2.10.1.jar” MongoDBJDBC
Connect to database successfully
Authentication: true
If the username and password are correct, the value of Authentication is true.
Create Collection
We can use createCollection() in the com.mongodb.DB class to create collections
The code snippet is as follows:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// Connect to mongodb service
MongoClient mongoClient = new MongoClient( “localhost”, 27017 );
// Connect to database
DB db = mongoClient.getDB( “test” );
System.out.println(“Connect to database successfully”);
boolean auth = db.authenticate(myUserName, myPassword);
&nbsnbsp; }
}
Compile and run the above program, the output is as follows:
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Inserted Document: 1
{
“_id” : ObjectId(7df78ad8902c),
“title”: “MongoDB”,
“description”: “database”,
“likes”: 100,
“url”: “http://www.w3cschool.cc/mongodb/”,
“by”: “w3cschool.cc”
}
Update Documentation
You can update documents in the collection using the update() method of the com.mongodb.DBCollection class.
The code snippet is as follows:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// Connect to Mongodb service
MongoClient mongoClient = new MongoClient( “localhost”, 27017 );
// Connect to your database
DB db = mongoClient.getDB( “test” );
System.out.println(“Connect to database successfully”);
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println(“Authentication: “+auth);
DBCollection coll = db.getCollection(“mycol”);
System.out.println(“Collection mycol selected successfully”);
DBCursor cursor = coll.find();
while (cursor.hasNext()) {
DBObject updateDocument = cursor.next();
updateDocument.put(“likes”,”200″)
Col1.update(updateDocument);
}
System.out.println(“Document updated successfully”);
Cursor = coll.find();
int i=1;
while (cursor.hasNext()) {
System.out.println(“Updated Document: “+i);
System.out.println(cursor.next());
i++;
}
}catch(Exception e){
System.err.println( e.getClass().getName() + “: ” + e.getMessage() );
}
}
}
Compile and run the above program, the output is as follows:
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document updated successfully
Updated Document: 1
{
“_id” : ObjectId(7df78ad8902c),
“title”: “MongoDB”,
“description”: “database”,
“likes”: 100,
“url”: “http://www.w3cschool.cc/mongodb/”,
“by”: “w3cschool.cc”
}
Delete first document
To delete the first document in the collection, first you need to use the com.mongodb.DBCollection class
findOne() method to get the first document, and then remove it using the remove method.
The code snippet is as follows:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// Connect to Mongodb service
MongoClient mongoClient = new MongoClient( “localhost”, 27017 );
// Connect to your database
DB db = mongoClient.getDB( “test” );
System.out.println(“Connect to database successfully”);
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println(“Authentication: “+auth);
DBCollection coll = db.getCollection(“mycol”);
System.out.println(“Collection mycol selected successfully”);
DBObject myDoc = coll.findOne();
Col1. remove(myDoc);
DBCursor cursor = coll.find();
int i=1;
while (cursor.hasNext()) {
System.out.println(“Inserted Document: “+i);
System.out.println(cursor.next());
i++;
}
System.out.println(“Document deleted successfully”);
}catch(Exception e){
System.err.println( e.getClass().getName() + “: ” + e.getMessage() );
}
}
}
Compile and run the above program, the output is as follows:
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document deleted successfully
You can also use save(), limit(), skip(), sort() and other methods to operate the MongoDB database.
In the ngodb.DBCollection class
findOne() method to get the first document, and then remove it using the remove method.
The code snippet is as follows:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// Connect to Mongodb service
MongoClient mongoClient = new MongoClient( “localhost”, 27017 );
// Connect to your database
DB db = mongoClient.getDB( “test” );
System.out.println(“Connect to database successfully”);
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println(“Authentication: “+auth);
DBCollection coll = db.getCollection(“mycol”);
System.out.println(“Collection mycol selected successfully”);
DBObject myDoc = coll.findOne();
Col1. remove(myDoc);
DBCursor cursor = coll.find();
int i=1;
while (cursor.hasNext()) {
System.out.println(“Inserted Document: “+i);
System.out.println(cursor.next());
i++;
}
System.out.println(“Document deleted successfully”);
}catch(Exception e){
System.err.println( e.getClass().getName() + “: ” + e.getMessage() );
}
}
}
Compile and run the above program, the output is as follows:
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document deleted successfully
You can also use save(), limit(), skip(), sort() and other methods to operate the MongoDB database.