How to Add Fields in a MongoDB Array using Java

Introduction

When you’re working with data in MongoDB, it’s likely that you’ll have to add a new field to a document at some point. Fortunately, adding fields in a MongoDB array is a simple task that can be accomplished in just a few lines of code. In this step-by-step tutorial, we’ll show you how to add a new field in a MongoDB document array.

Prerequisites

Before we dive into the Java code, let’s review the system requirements that will be needed for this task. There are a few important prerequisites:

  • First, you must make sure that MongoDB and the MongoDB Java driver have both been properly configured beforehand.

  • You must also ensure that the latest Java JDK has been properly installed and configured before proceeding.

  • Finally, you must confirm that the MongoDB service is running.

NOTE: Throughout this article, we assume that the MongoDB version being used is 4.0 and the MongoDB Java Driver is 3.8.2.

The MongoDB Dataset

If you plan to follow along with the code examples in this article, it’s important to use the same data. The dataset shown below will be used throughout this tutorial:

{
"_id" : ObjectId("5cef50eb3fd48a2c4adb0ceb"),
"customerName" : "Purisa",
"customer-address" : [
{
"type" : "primary-address"
"street" : "#21 Easy Street",
"city" : "Easy",
"state" : "PH",
"zip" : "57733",
}
}

Set up access to the MongoDB deployment

Now that we’ve confirmed all the system requirements and created our sample dataset, we can begin looking at the code. The fist step is to instantiate a MongoClient object. When we do this, we explicitly specify the hostname and the port number:

MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");

In this example, we’re running MongoDB locally, on the default port 27017.

Set up access to the MongoDB database

Next, we’ll access a database. You can use the command shown below to access the MongoDB database "customerDatabase" by using the getDatabase() method:

MongoDatabase db = mongo.getDatabase("customerDatabase");

Set up the access to the MongoDB collection

Once we’ve accessed a MongoDB database, we can then access any collections available within that database. You can use the command shown below to access the "customerCollection" collection:

MongoCollection<document> warColl = db.getCollection("customerCollection");

Adding a new MongoDB document within an existing MongoDB document

In the next example, we’ll use the MongoDB addtoset method to add a new field to an existing MongoDB document.

The addToSet() accepts a string-object pair. You can see how this works in the code shown below:

Document newAddress = new Document().append("type", "secondaryAddress")
.append("street", "#24 niceton")
.append("city","Nice");

db.getCollection("customerCollection").updateOne(eq("customerName", "Purisa"),Updates.addToSet("customer-address", newAddress));

You can that the value of newAddress is actually a composition of fields forming a single document, which will be added within a MongoDB document.

After you execute this code, the results should look something like the following:

"_id" : ObjectId("5cef50eb3fd48a2c4adb0ceb"),
"customerName" : "Purisa",
"customer-address" : [
{
"street" : "#21 Easy Street",
"city" : "Easy",
"state" : "PH",
"zip" : "57733",
"type" : "primary-address"
},
{
"type" : "secondaryAddress",
"street" : "#24 niceton",
"city" : "Nice"
}
]
}

Adding new MongoDB fields in an Existing MongoDB Document

You can use the $set operator to replace a field with a specified value; however, in this tutorial, the MongoDB set function serves to add a new MongoDB field within the existing document if the specified field does not exist:

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

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

The code shown above will add the field corner with a value of #15 2Easy Street within the customer-address document.

After executing this code, the results will look something like the following:

"_id" : ObjectId("5cef50eb3fd48a2c4adb0ceb"),
"customerName" : "Purisa",
"customer-address" : [
{
"street" : "#21 Easy Street",
"city" : "Easy",
"state" : "PH",
"zip" : "57733",
"corner" : "#15 2Easy Street",
"type" : "primary-address"
},
{
"type" : "secondaryAddress",
"street" : "#24 niceton",
"city" : "Nice"
}
]
}

Conclusion

If you’re a Java developer working with MongoDB, you know that adding new fields to an existing document is a common task. The examples we reviewed in this tutorial showed that there are a few different ways to add fields to a MongoDB array. Whether you choose to work with the $set operator or the addToSet() method, you’ll have no trouble adding fields in a MongoDB array using Java.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed Redis,
MongoDB & Elasticsearch

Get Started

OR

Try CockroachDB
in Beta

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.