Java insert value to array in MongoDB

share link

by Abdul Rawoof A R dot icon Updated: Apr 11, 2023

technology logo
technology logo

Solution Kit Solution Kit  

To insert a value array in MongoDB, we can use the $push operator to add or append a value to an array. This operator can be used with various modifiers in Java, one of which is the $position modifier.


We can add data or information in MongoDB by using MongoDB's insert() method and save() methods. To update or insert an array of objects in MongoDB, perform an update operation on all embedded array elements of each document that matches our query or requirement and use the filtered positional operator. This filtered positional operator specifies the most matching array elements or values in the updated document or database. To update a value in the array, use the updateOne() method to update a single value to the array. If we need to add more than one or two values to the array, use the updateMany() method. We always recommend you use updateMany() method to update multiple values to the array.


Here is an example of how to insert value to an array in MongoDB in Java:

Fig: Preview of the output that you will get on running this code from your IDE.

Code

In this solution we're using mongo-java-driver library.

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;

import org.bson.Document;
import org.bson.conversions.Bson;

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;

public class MongoDbPush {
  public static void main(String[] args)
  {
    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("pushExampleDb");
    MongoCollection<Document> collection = database.getCollection("pushExampleCollection");

    String sensorType = "Temperature";

    // try to load existing document from MongoDB
    Document document = collection.find(eq("Sensor Type", sensorType)).first();
    if(document == null)
    {
      // no test document, let's create one!
      document = new Document("Sensor Type", sensorType);

      // insert it into MongoDB
      collection.insertOne(document);

      // read it back from MongoDB
      document = collection.find(eq("Sensor Type", sensorType)).first();
    }

    // see what it looks like in JSON (on the first run you will notice that it has got an "_id" but no "Subscribed Topics" array yet)
    System.out.println(document.toJson());

    // update the document by adding an entry to the "Subscribed Topics" array
    Bson filter = eq("Sensor Type", sensorType);
    Bson change = push("Subscribed Topics", "Some Topic");
    collection.updateOne(filter, change);

    // read one more time from MongoDB
    document = collection.find(eq("Sensor Type", sensorType)).first();

    // see what the document looks like in JSON (on the first run you will notice that the "Subscribed Topics" array has been created and has got one element in it)
    System.out.println(document.toJson());

    mongoClient.close();
  }
}

Instructions

Follow the steps carefully to get the output easily.

  1. Install IntelliJ Community Edition and Java on your computer.
  2. Create a new Maven project.
  3. Add 'mongo-java-driver' dependency in 'pom.xml' file.
  4. Create a Java class file(eg: MongoDbPush).
  5. Copy the snippet using the 'copy' button and paste it into that file.
  6. Run the file using run button.


I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.


I found this code snippet by searching for 'java insert value to array in mongodb' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in IntelliJ 2023.1.
  2. The solution is tested on Java JDK 20.
  3. mongo-java-driver 4.8.2.


Using this solution, we are able to insert value to array in mongodb in Java with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to insert value to array in mongodb in Java.

Dependent Library

Java doticonstar image 2538 doticonVersion:r4.9.0doticon
License: Permissive (Apache-2.0)

The official MongoDB drivers for Java, Kotlin, and Scala

Support
    Quality
      Security
        License
          Reuse

            mongo-java-driverby mongodb

            Java doticon star image 2538 doticonVersion:r4.9.0doticon License: Permissive (Apache-2.0)

            The official MongoDB drivers for Java, Kotlin, and Scala
            Support
              Quality
                Security
                  License
                    Reuse

                      You can also search for any dependent libraries on kandi like 'mongo-java-driver'.

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page.


                      See similar Kits and Libraries