How to Work with Embedded Document in MongoDB Collection

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

Introduction

This is “Part Two” of the “How to Work with embedded documents in a MongoDB Collection” tutorial. This second part of the tutorial will demonstrate how to:

  1. Create a simple embedded MongoDB document.
  2. Update a field of an embedded MongoDB document.
  3. Delete an embedded MongoDB document.

All of the examples in this tutorial will be using MongoDB version 4.0 and MongoDB Java Driver version 3.8.2.

Prerequisites

  • The MongoDB service must be properly installed, configured and running.

  • The successful completion of Part One of this tutorial.

NOTE: All of the examples in this tutorial use MongoDB version 4.0 and MongoDB Java Driver version 3.8.2

1
2
3
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("customerDB");
MongoCollection<document> collection = db.getCollection("customerCollection");
  • The above code will create a connection with the MongoDB deployment and access both the database (customerDB) and the specified collection (customerCollection).

How to Insert an Embedded MongoDB Document using Java.

  • The following code will insert an embedded MongoDB document in a MongoDB collection in an array format using Arrays(). However, the structure used in the following example is a more simplified version of that used in Part One of this tutorial:

NOTE: As explained previously, the below document schema is for demonstration purposes only, and the schema may be modified as deemed necessary.

1
2
3
4
5
6
7
8
9
10
Document doc = new Document("customerName","Abishai Galisanao")
.append("customer-address", Arrays.asList(( new Document("primaryAddress",new Document("street", "#21 Easy Street")
.append ("city", "Easy")
.append("state", "PH")
.append("zip", "57733"))),
new Document("secondaryAddress",new Document("street", "#54 Nice Street")
.append ("city", "Niceton")
.append("state", "PH")
.append("zip", "14344"))));
db.getCollection("customerCollection").insertOne(doc);
  • Take note of how useful this new Document is, allowing the user to create another document inside a MongoDB document.

  • Execute the following command in the Mongo shell to confirm the above operation was successful:

1
db.customerCollection.find().pretty()
  • The results should resemble something that looks like the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
"_id" : ObjectId("5ce9f3773fd48a30bd80db41"),
"customerName" : "Abishai Galisanao",
"customer-address" : [
{
"primaryAddress" : {
"street" : "#21 Easy Street",
"city" : "Easy",
"state" : "PH",
"zip" : "57733"
}
},
{
"secondaryAddress" : {
"street" : "#54 Nice Street",
"city" : "Niceton",
"state" : "PH",
"zip" : "14344"
}
}
]
}
  • The above result shows an embedded document within a MongoDB document, with the customer-address field holding two documents.

How to Update an Embedded MongoDB Document using Java

  • The following code will update an embedded MongoDB document using the MongoDB “Dot Notation”.

Dot Notation — MongoDB permits the user to access the elements of an array and access the fields within a MongoDB embedded document, as shown in the following example:

1
2
3
4
5
6
7
8
BasicDBObject query = new BasicDBObject();
query.put("customerName","Abishai Galisanao");

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

db.getCollection("customerCollection").updateOne(
query,update);
  • The below image displays the hierarchy of the customer-address document. The customer-address field is composed of two documents embedded in it, namely primaryAddress and secondaryAddress with an index position of 0 and 1, respectively.

MongoDB embedded document

  • The above code attempts to make an update to the street field within the secondaryAddress document.

Analyzing the Update Operation

  • The code:
1
update.put("$set", new BasicDBObject("customer-address.1.secondaryAddress.street", "#15 2Easy Street"));
  • The above code will access the customer-document field with an index of 1, that is the secondaryAddress and will eventually access the field street using a “dot notation” and will then set the new value as specified in the code.

  • Use the MongoDB shell to confirm the command executed properly.

  • The results should resemble something that looks like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
"_id" : ObjectId("5ce9f9313fd48a33315f45bb"),
"customerName" : "Abishai Galisanao",
"customer-address" : [
{
"primaryAddress" : {
"street" : "#21 Easy Street",
"city" : "Easy",
"state" : "PH",
"zip" : "57733"
}
},
{
"secondaryAddress" : {
"street" : "#15 2Easy Street",
"city" : "Niceton",
"state" : "PH",
"zip" : "14344"
}
}
]
}
  • Note how the value of the street field in the secondaryAddress now changes.

How to Delete a field within a MongoDB Embedded Document.

  • The following code will delete the street field:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
MongoDatabase db = mongo.getDatabase("customerDatabase");
BasicDBObject query = new BasicDBObject();
query.put("customerName","Abishai Galisanao");

BasicDBObject condition = new BasicDBObject();
condition.put("street","#15 2Easy Street");

BasicDBObject array = new BasicDBObject();
array.put("customer-address.1.secondAddress.street", condition);

BasicDBObject update = new BasicDBObject();
update.put("$unset", array);
db.getCollection("customerCollection").updateOne(
query,update);
  • Using the $unset operator will delete the matching field within the MongoDB document.
  • Execute the following command in the Mongo shell to verify the operation in the above example was successful:
1
db.customerCollection.find().pretty()
  • The results should resemble something that looks like the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"_id" : ObjectId("5ce9f9313fd48a33315f45bb"),
"customerName" : "Abishai Galisanao",
"customer-address" : [
{
"primaryAddress" : {
"street" : "#21 Easy Street",
"city" : "Easy",
"state" : "PH",
"zip" : "57733"
}
},
{
"secondaryAddress" : {
"city" : "Niceton",
"state" : "PH",
"zip" : "14344"
}
}
]
}
  • Note how the street field is now deleted from the above example.

Conclusion

This was the second part of the “How to Work with embedded documents in a MongoDB Collection” tutorial. The tutorial explained the basic ways of inserting, updating and deleting a specific field in an embedded document in a MongoDB collection. The examples shows simple ways of creating and editing embedded MongoDB documents using Java and deleting fields in documents in a MongoDB Collection using Java. Remember, all of the examples in this tutorial were executed using MongoDB version 4.0 and MongoDB Java Driver version 3.8.2.

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.