MongoDB Java
Environment Setup
To use MongoDB in a Java program, you need to ensure that you have Java environment and MongoDB JDBC driver installed.
This section is suitable for Mongo 3.x and above versions.
You can refer to our Java Tutorial to install Java. Now, let's check if you have the MongoDB JDBC driver installed.
-
First, you must download the mongo jar package from: https://mongodb.github.io/mongo-java-driver/, make sure to download the latest version.
You need to include mongo-java-driver-3.2.2.jar (find the appropriate version) in your classpath.
Domestic mongodb-driver jar download address: http://central.maven.org/maven2/org/mongodb/mongo-java-driver/
Connecting to the Database
To connect to the database, you need to specify the database name. If the specified database does not exist, mongo will automatically create it.
The Java code to connect to the database is as follows:
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// Connect to mongodb service
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
Now, let's compile and run the program to connect to the database mycol.
You can change the MongoDB JDBC driver path according to your actual environment.
This example places the MongoDB JDBC startup package mongo-java-driver-3.2.2.jar in the local directory:
$ javac -cp .:mongo-java-driver-3.2.2.jar MongoDBJDBC.java
$ java -cp .:mongo-java-driver-3.2.2.jar MongoDBJDBC
Connect to database successfully
Authentication: true
In this example, the Mongo database does not require username and password verification. If your Mongo requires verification, you can use the following code:
import java.util.ArrayList;
import java.util.List;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args){
try {
// Connect to MongoDB service. If it's a remote connection, replace "localhost" with the server's IP address
// ServerAddress() takes two parameters: server address and port
ServerAddress serverAddress = new ServerAddress("localhost",27017);
```java
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
// MongoCredential.createScramSha1Credential() takes three parameters: username, database name, password
MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
// Obtain MongoDB connection through authentication
MongoClient mongoClient = new MongoClient(addrs, credentials);
// Connect to the database
MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
System.out.println("Connected to database successfully");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Create a Collection
We can use the createCollection()
method in the com.mongodb.client.MongoDatabase
class to create a collection.
The code snippet is as follows:
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String args[]) {
try {
// Connect to the MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to the database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connected to database successfully");
mongoDatabase.createCollection("test");
System.out.println("Collection created successfully");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program will output the following:
Connected to database successfully
Collection created successfully
Retrieve a Collection
We can use the getCollection()
method of the com.mongodb.client.MongoDatabase
class to retrieve a collection.
The code snippet is as follows:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String args[]) {
try {
Connect to database successfully
Collection test selected successfully
Inserting Documents
We can use the insertMany()
method of the com.mongodb.client.MongoCollection
class to insert documents.
Here is a code snippet:
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String args[]) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Insert document
/**
* 1. Create document org.bson.Document with key-value pairs
* 2. Create a list of documents List<Document>
* 3. Insert the list of documents into the database collection with mongoCollection.insertMany(List<Document>)
* To insert a single document, use mongoCollection.insertOne(Document)
*/
Document document = new Document("title", "MongoDB")
.append("description", "database")
.append("likes", 100)
.append("by", "Fly");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
collection.insertMany(documents);
System.out.println("Document inserted successfully");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program outputs:
Connect to database successfully
Collection test selected successfully
Document inserted successfully
Connect to database successfully
Collection test selected successfully
Document inserted successfully
Retrieve All Documents
We can use the find()
method from the com.mongodb.client.MongoCollection
class to retrieve all documents in a collection.
This method returns a cursor, so you need to iterate through this cursor.
Here is the code snippet:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Retrieve all documents
/**
* 1. Get iterator FindIterable<Document>
* 2. Get cursor MongoCursor<Document>
* 3. Iterate through the cursor to retrieve the documents
*/
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program will produce the following output:
Connect to database successfully
Collection test selected successfully
Document{{_id=56e65fb1fd57a86304fe2692, title=MongoDB, description=database, likes=100, by=Fly}}
Update Document
You can use the updateMany()
method from the com.mongodb.client.MongoCollection
class to update documents in a collection.
Here is the code snippet:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Retrieve all documents
/**
* 1. Get iterator FindIterable<Document>
* 2. Get cursor MongoCursor<Document>
* 3. Iterate through the cursor to retrieve the documents
*/
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program will produce the following output:
Connect to database successfully
Collection test selected successfully
Document{{_id=56e65fb1fd57a86304fe2692, title=MongoDB, description=database, likes=100, by=Fly}}
Update Document
You can use the updateMany()
method from the com.mongodb.client.MongoCollection
class to update documents in a collection.
Here is the code snippet:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Retrieve all documents
/**
* 1. Get iterator FindIterable<Document>
* 2. Get cursor MongoCursor<Document>
* 3. Iterate through the cursor to retrieve the documents
*/
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program will produce the following output:
Connect to database successfully
Collection test selected successfully
Document{{_id=56e65fb1fd57a86304fe2692, title=MongoDB, description=database, likes=100, by=Fly}}
Update Document
You can use the updateMany()
method from the com.mongodb.client.MongoCollection
class to update documents in a collection.
Here is the code snippet:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Retrieve all documents
/**
* 1. Get iterator FindIterable<Document>
* 2. Get cursor MongoCursor<Document>
* 3. Iterate through the cursor to retrieve the documents
*/
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program will produce the following output:
Connect to database successfully
Collection test selected successfully
Document{{_id=56e65fb1fd57a86304fe2692, title=MongoDB, description=database, likes=100, by=Fly}}
Update Document
You can use the updateMany()
method from the com.mongodb.client.MongoCollection
class to update documents in a collection.
Here is the code snippet:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Retrieve all documents
/**
* 1. Get iterator FindIterable<Document>
* 2. Get cursor MongoCursor<Document>
* 3. Iterate through the cursor to retrieve the documents
*/
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program will produce the following output:
Connect to database successfully
Collection test selected successfully
Document{{_id=56e65fb1fd57a86304fe2692, title=MongoDB, description=database, likes=100, by=Fly}}
Update Document
You can use the updateMany()
method from the com.mongodb.client.MongoCollection
class to update documents in a collection.
Here is the code snippet:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Retrieve all documents
/**
* 1. Get iterator FindIterable<Document>
* 2. Get cursor MongoCursor<Document>
* 3. Iterate through the cursor to retrieve the documents
*/
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program will produce the following output:
Connect to database successfully
Collection test selected successfully
Document{{_id=56e65fb1fd57a86304fe2692, title=MongoDB, description=database, likes=100, by=Fly}}
Update Document
You can use the updateMany()
method from the com.mongodb.client.MongoCollection
class to update documents in a collection.
Here is the code snippet:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Retrieve all documents
/**
* 1. Get iterator FindIterable<Document>
* 2. Get cursor MongoCursor<Document>
* 3. Iterate through the cursor to retrieve the documents
*/
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program will produce the following output:
Connect to database successfully
Collection test selected successfully
Document{{_id=56e65fb1fd57a86304fe2692, title=MongoDB, description=database, likes=100, by=Fly}}
Update Document
You can use the updateMany()
method from the com.mongodb.client.MongoCollection
class to update documents in a collection.
Here is the code snippet:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Retrieve all documents
/**
* 1. Get iterator FindIterable<Document>
* 2. Get cursor MongoCursor<Document>
* 3. Iterate through the cursor to retrieve the documents
*/
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program will produce the following output:
Connect to database successfully
Collection test selected successfully
Document{{_id=56e65fb1fd57a86304fe2692, title=MongoDB, description=database, likes=100, by=Fly}}
Update Document
You can use the updateMany()
method from the com.mongodb.client.MongoCollection
class to update documents in a collection.
Here is the code snippet:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Retrieve all documents
/**
* 1. Get iterator FindIterable<Document>
* 2. Get cursor MongoCursor<Document>
* 3. Iterate through the cursor to retrieve the documents
*/
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
```java
import com.mongodb.client.model.Filters;
public class MongoDBJDBC {
public static void main(String args[]) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connected to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Collection test selected successfully");
// Update documents where likes=100 to likes=200
collection.updateMany(Filters.eq("likes", 100), new Document("$set", new Document("likes", 200)));
// Retrieve and view results
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program outputs the following results:
Connected to database successfully
Collection test selected successfully
Document{{_id=56e65fb1fd57a86304fe2692, title=MongoDB, description=database, likes=200, by=Fly}}
Deleting the First Document
To delete the first document in the collection, you first need to get the first document using the findOne()
method of the com.mongodb.DBCollection
class, and then use the remove
method to delete it.
The code snippet is as follows:
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class MongoDBJDBC {
public static void main(String args[]) {
try {
// Connect to MongoDB service
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Connect to database
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connected to database successfully");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("Successfully selected collection test");
// Delete the first document that matches the condition
collection.deleteOne(Filters.eq("likes", 200));
// Delete all documents that match the condition
collection.deleteMany(Filters.eq("likes", 200));
// Retrieve and view the results
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
} catch(Exception e){
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
Compiling and running the above program, the output is as follows:
Connect to database successfully
Successfully selected collection test
For more operations, refer to: http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/
Reference document: http://blog.csdn.net/ererfei/article/details/50857103 ```