In the last MongoDB example, How documents are represented in MongoDB Java Driver?, we’ve seen how MongoDB JSON documents are represented in MongoDB Java driver.
Using this knowledge it is time for us to learn how to insert documents into MongoDB collections. We will create a code snippet that will insert documents into the teachers
collections in the school
database. We will see the complete code snippet first followed by a detail description of the code snippet. So, let’s begin with the code snippet.
package org.kodejava.mongodb;
import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.json.JsonMode;
import org.bson.json.JsonWriterSettings;
import org.bson.types.ObjectId;
import java.util.Arrays;
public class MongoDBInsertDocument {
public static void main(String[] args) {
// Creates MongoDB client instance.
MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));
// Gets the school database from the MongoDB instance.
MongoDatabase database = client.getDatabase("school");
// Gets the teachers collection from the database.
MongoCollection<Document> teachers = database.getCollection("teachers");
teachers.drop();
// Creates a document to be stored in the teachers collections.
Document document = new Document("firstName", "John")
.append("lastName", "Doe")
.append("subject", "Computer Science")
.append("languages", Arrays.asList("Java", "C", "C++"))
.append("email", "[email protected]")
.append("address",
new Document("street", "Main Apple St. 12")
.append("city", "New York")
.append("country", "USA"));
// Prints the value of the document.
JsonWriterSettings settings = JsonWriterSettings.builder()
.indent(true)
.outputMode(JsonMode.RELAXED)
.build();
System.out.println(document.toJson(settings));
// Inserts the document into the collection in the database.
teachers.insertOne(document);
// Prints the value of the document after inserted in the collection.
System.out.println(document.toJson(settings));
}
}
The snippet should be easy to understand. But I will explain about it a little more down here. In the beginning of the code snippet we begin with the following lines:
// Creates MongoDB client instance.
MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));
This is how we bootstrap / start the MongoDB Java Driver. It connects to MongoDB server at localhost
port 27017
. If you omit using this ServerAddress
class it will also connect to localhost
port 27017
as the default. On the next lines you can see the following codes.
// Gets the school database from the MongoDB instance.
MongoDatabase database = client.getDatabase("school");
// Gets the teachers collection from the database.
MongoCollection<Document> teachers = database.getCollection("teachers");
teachers.drop();
This code snippet tells you how to get the database, the school
database. We get the database using the client.getDatabase()
method call and passing the database name as the argument. The reference to this database then stored in a variable called database
. After having the database
we can then access the teachers
collections by calling the database.getCollection()
method.
You also notice that we call collection.drop()
, which will clear the collection. We use this for our example purpose only, just to make sure that every time we execute our code snippet the collection will be cleaned before we insert some document.
Next, we create the document to be stored in the teachers
collections. We define a variable called document
with Document
type which refer to an instance of org.bson.Document
type. And we add some fields in the document, and array type field and another embedded document.
// Creates a document to be stored in the teachers collections.
Document document = new Document("firstName", "John")
.append("lastName", "Doe")
.append("subject", "Computer Science")
.append("languages", Arrays.asList("Java", "C", "C++"))
.append("email", "[email protected]")
.append("address",
new Document("street", "Main Apple St. 12")
.append("city", "New York")
.append("country", "USA"));
In the last three lines we do the following:
// Prints the value of the document.
JsonWriterSettings settings = JsonWriterSettings.builder()
.indent(true)
.outputMode(JsonMode.RELAXED)
.build();
System.out.println(document.toJson(settings));
// Inserts the document into the collection in the database.
teachers.insertOne(document);
// Prints the value of the document after inserted in the collection.
System.out.println(document.toJson(settings));
In the first print out we will see the document
as defined in the previous lines using the org.bson.Document
with all the defined field values. Then it followed by calling the collection.insertOne()
method which will insert the document into the collections.
In the last line we print out the document
once again. You might see that the result is almost the same as the first print out, but you will notice that after inserted into the collection the document
now have another field, which is the _id
field assigned by the Java Driver as the object id of the document. The _id
is added automatically if we didn’t define the _id
field in the document. It is essentially the same as if we define the document using the following code, where _id
it a type of org.bson.types.ObjectId
.
Document document = new Document("_id", new ObjectId());
And these are the actual output of the code above:
{
"firstName": "John",
"lastName": "Doe",
"subject": "Computer Science",
"languages": [
"Java",
"C",
"C++"
],
"email": "[email protected]",
"address": {
"street": "Main Apple St. 12",
"city": "New York",
"country": "USA"
}
}
{
"firstName": "John",
"lastName": "Doe",
"subject": "Computer Science",
"languages": [
"Java",
"C",
"C++"
],
"email": "[email protected]",
"address": {
"street": "Main Apple St. 12",
"city": "New York",
"country": "USA"
},
"_id": {
"$oid": "6191261ad2c0ec541c3edba2"
}
}
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.11</version>
</dependency>
</dependencies>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Hi its good work I am also working on this topic MongoDB insert a document http://programmershelper.com/mongodb-insert-document-guideline