Embedded Documents in a MongoDB Collection

Introduction

If you’re new to using MongoDB, you may not have much experience working with embedded documents. However, it’s worth taking the time to learn how to use them– the embedded document model is a powerful concept, allowing you to store all kinds of related information in a single document. This “denormalized” database structure offers better performance and often allows applications to make fewer queries. In this tutorial, we’ll provide instructions on working with an embedded document in a MongoDB collection.

Prerequisites

Before we can look at some examples, it’s important to review the system requirements. For this task, there are a few critical prerequisites that must be in place before proceeding:

  • Both MongoDB and the MongoDB Java driver must be properly configured beforehand.

  • The latest Java JDK must be properly installed and configured beforehand.

  • Finally, the MongoDB service must be running.

NOTE: For the examples depicted in this tutorial, we assume that the MongoDB version used is 4.0 and MongoDB Java Driver is 3.8.2.

What is an Embedded MongoDB Document?

At this point, we’re just about ready to dive into some code examples, but first, let’s take a moment to understand embedded documents and how they work. An embedded, or nested, MongoDB Document is a normal document that’s nested inside another document within a MongoDB collection.

The following shows an a sample of an embedded document:

{
"_id" : ObjectId("5ce8050c3fd48a59557122ca"),
"customerName" : "Yeshua Galisanao",
"customer-address" : [
{
"primaryAddress" : [
{
"street" : "#43 Easy Street",
"city" : "Niceton",
"state" : "PH",
"zip" : "57733"
}
]
},
{
"secondaryAddress" : [
{
"street" : "43",
"city" : "seattle",
"state" : "PH",
"zip" : "57667"
}
]
}
]
}

Embedded documents are particularly useful when a one-to-many relationship exists between documents. In the example shown above, we see that a single customer has multiple addresses associated with him. The nested document structure makes it easy to retrieve complete address information about this customer with just a single query.

When to Use an Embedded MongoDB Document

There are a few key points to consider before using an embedded document structure in MongoDB:

  1. Will the MongoDB child documents be needed every time the parent MongoDB document is required via a query?
  2. The deletion of the parent MongoDB document will also delete the child MongoDB document– will this be acceptable for your data set?
  3. In MongoDB, a document’s size must be smaller than the maximum BSON size for documents, which is 16 megabytes. If document size will not be an issue, then an embedded document may be feasible as the MongoDB document structure.

The Connection to the MongoDB Deployment

Let’s turn our attention to the Java code now. Our example begins with a connection to MongoDB:

MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("customerDB");
MongoCollection<document> collection = db.getCollection("customerCollection");

The code shown above establishes a connection to the MongoDB deployment. It then proceeds to access both the database (customerDB) and a collection (customerCollection).

Insert a Embedded MongoDB Document using Java

Next, let’s try inserting an embedded document into our MongoDB collection. The below code will insert a embedded MongoDB document in an Array format using Arrays():

NOTE The document schema shown below is for demo purposes only.

Document nestDoc = new Document("customerName", "Yeshua Galisanao")
.append("customer-address",
Arrays.asList(
new Document(
"primaryAddress",Arrays.asList(
new Document("street", "#43 Nice Street")
.append ("city", "Niceton")
.append("state", "PH")
.append("zip", "57733"))
),
new Document("secondaryAddress",
Arrays.asList(
new Document("street", "#54 Easy Street")
.append("city", "Easyton")
.append("state", "PH")
.append("zip", "57667")
)
)));
db.getCollection("customerCollection").insertOne(nestDoc);

With the use of new Document, MongoDB allows the user to create another document, putting a BasicDBObject within a BasicDBObj.

To verify if the above operation executed successfully, use the command shown below in the Mongo shell:

db.customerCollection.find().pretty()

The results should look like the following:

{
"_id" : ObjectId("5ce88f1a3fd48a6e492ef61b"),
"customerName" : "Yeshua Galisanao",
"customer-address" : [
{
"primaryAddress" : [
{
"street" : "#43 Nice Street",
"city" : "Niceton",
"state" : "PH",
"zip" : "57733"
}
]
},
{
"secondaryAddress" : [
{
"street" : "#54 Easy Street",
"city" : "Easyton",
"state" : "PH",
"zip" : "57667"
}
]
}
]
}

The results depicted above show an embedded document within a MongoDB document. The customer-address field holds an array of two documents. An embedded document structure like this can frequently be seen in applications like e-commerce, where a customer often has different addresses for shipping purposes.

Update an Embedded MongoDB Document using Java

Now that we’ve seen how to insert an embedded document, let’s try to update one. The code shown below will update an embedded MongoDB document using MongoDB “Dot Notation”.

Dot Notation — MongoDB uses dot notation to allow users to access the elements of an array and to be able to access the fields that exist within an embedded document.

BasicDBObject query = new BasicDBObject();
query.put("customerName","Yeshua Galisanao");

BasicDBObject update = new BasicDBObject();
update.put("$set", new BasicDBObject("customer-address.1.secondaryAddress.0.street", "#15 2Easy Street"));

db.getCollection("customerCollection").updateOne(
query,update);

The image below shows the hierarchy of the customer-address document. The customer-address field contains two documents embedded in it: primaryAddress and secondaryAddress. In terms of an array, these have the respective index positions of 0 and 1.

The primaryAddress and secondaryAddress documents are composed of fields that have their own index position, which can be seen below. In our example shown above, the code updates the street field within the secondaryAddress document:

MongoDB embedded document structure

Dissecting the Update Operation

Let’s take a close look at the following code:

update.put("$set", new BasicDBObject("customer-address.1.secondaryAddress.0.street", "#15 2Easy Street"));

This code will access the customer-document field that has an index of 1; in this case, that’s the secondaryAddress. Within the secondaryAddress, it will access the field named street in the index position 0, then it will set the new value that is specified in the code.

To verify using the MongoDB shell:

The results should look like the following:

{
"_id" : ObjectId("5ce88f1a3fd48a6e492ef61b"),
"customerName" : "Yeshua Galisanao",
"customer-address" : [
{
"primaryAddress" : [
{
"street" : "#43 Nice Street",
"city" : "Niceton",
"state" : "PH",
"zip" : "57733"
}
]
},
{
"secondaryAddress" : [
{
"street" : "#15 2Easy Street",
"city" : "Easyton",
"state" : "PH",
"zip" : "57667"
}
]
}
]
}

Notice that the value of the street field in secondaryAddress has been successfully updated.

Conclusion

When you have documents where a one-to-many relationship exists, it can be helpful to use an embedded, or nested, document structure. Working with an embedded document in a MongoDB collection isn’t difficult as long as you understand how this unique structure should be used. This tutorial showed you how to insert and update an embedded MongoDB Document using Java. Be sure to move on to Part 2 of this tutorial to learn even more about how to interact with embedded MongoDB documents.

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.