Inserting a Document in MongoDB Using JAVA

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

MongoDB stores documents in BSON form. All of the documents in MongoDB are a record that is a data structure made up of fields and value pairs. MongoDB documents are comparable to JSON objects and the values of fields can include other documents and/or arrays of documents. Just as you use JSON like structure to symbolize data, you can also populate data in a BSON document object and then insert it into the MongoDB collection. MongoDB stores documents in collections that are similar to tables in relational databases. This tutorial will show you how to insert both single and multiple documents into the MongoDB collection using JAVA. You must have MongoDB and the compatible MongoDB JAVA driver properly installed and configured on your machine before inserting a document in MongoDB using JAVA.

Prerequisites

  • First, before you can begin inserting a document in MongoDB using JAVA, you will need to confirm you have MongoDB and the compatible MongoDB JAVA driver properly installed and configured on your machine.

How to Start the MongoDB Daemon

  • Begin by opening your terminal by pressing the Ctrl + Alt + T keys.

  • Next, start the MongoDB service and confirm the status using the below command.

  • You should use the sudo command to avoid permission-related issue while starting the MongoDB service.
1
2
sudo systemctl start mongod
sudo systemctl status mongod
  • The above command should return data that resembles the following:
1
2
3
4
5
6
7
8
9
● mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset:
   Active: active (running) since Sat 2019-05-18 10:10:52 PST; 2s ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 8408 (mongod)
   CGroup: /system.slice/mongod.service
           └─8408 /usr/bin/mongod --config /etc/mongod.conf

May 18 10:10:52 user-UX330UAK systemd[1]: Started MongoDB Database Server.

How to insert a single document into the MongoDB collection using JAVA

  • The following commands will insert a single document in a MongoDB collection using the insertOne() method:
1
2
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");  //(1)
MongoDatabase db = mongo.getDatabase("menuDB"); // (2)
  1. The first instance will connect to a MongoDB deployment.
  2. The second instance will connect to a MongoDB deployment database, namely “menuDB”.
1
2
3
4
5
Document doc = new Document("menuName", "Fiery Mexican Appetizers")
.append("menuId", "m01")
.append("lang", "English")
.append("ethnicity", "Mexican");
db.getCollection("menu").insertOne(doc);
  • MongoDB will store data as BSON documents, which are JSON formatted documents with a key-value pair.

  • This examples uses the insertOne() method to insert the fields within the declared collection name.

How to insert multiple documents into a MongoDB Collection using JAVA.

  • The following commands will allow you to insert multiple documents in a MongoDB collection using the bulkWrite() method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("menuDB");
MongoCollection<document> collection = db.getCollection("menuItem");
List<writemodel<document>> writes = new ArrayList<writemodel<document>>(); // (1)

writes.add(
new InsertOneModel<document>(
new Document("menuItem", "Mini Taco Dip Tostadas with Avocado Cream")
.append("category", "appetizer")
.append("menu_Refid", "m01")
.append("priceUsd", 35)
)
);

writes.add(
new InsertOneModel<document>(
new Document("menuItem", "Kelsey's Signature Salsa")
.append("category", "appetizer")
.append("menu_Refid", "m01")
.append("priceUsd", 25)
)
);

BulkWriteResult bulkWriteResult = collection.bulkWrite(writes); // (3)
  1. List<writemodel<document>> This command is used in bulk write operations in the MongoDB collection.
  2. InsertOneModel() method will insert a constructed document.
  3. Performs the multiple document insert using the .bulkWrite() method.

Conclusion

The article showed you various ways of inserting a document in MongoDB using JAVA. The commands shown in this tutorial can be used to insert a single document using the insertOne method or multiple documents in a MongoDB collection using the bulkWrite method. Bear in mind that MongoDB stores data as BSON documents, which are JSON formatted documents with a key-value pair. You must have MongoDB and the compatible MongoDB JAVA driver properly installed and configured on you machine before you will be able to insert a document in a MongoDB collection. Remember to use the sudo command to avoid permission-related issues whenever you start the MongoDB service.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.