Insert Array into a Collection using MongoClient in Java

share link

by vsasikalabe dot icon Updated: Mar 31, 2023

technology logo
technology logo

Guide Kit Guide Kit  

MongoDB is the most popular document-oriented NoSQL database. In MongoDB a document is a JSON-like objects data structure with field and value pairs. We can use different methods such as insert()insertOne() and insertMany() In order to insert documents into a MongoDB collection.

  1. insert() – Inserts a single document or multiple documents into a collection.
  2. insertOne() – Inserts a single document into a collection.
  3. insertMany() – Inserts multiple documents into a collection.


A push methods updates the array field with the value if the field is absent in the document. Use the each modifier with push method to add each element of the value separately. We have to prepare the documents to be inserted. Using the getCollection() method get the object of the collection into which you want to insert the documents. MongoDB uses BSON, or Binary JSON, it is the data format that is used to organize and store data. This data format includes all types of JSON data structure and adds dates, different size integers, ObjectIds, and binary data. And also the values are updated in the array using the collection.updateOne method.


This is an example of how to insert values to Array in MongoDB (Java):

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

Code

In this solution we have used MongoClient. The MongoClient is a class in the MongoDB Java driver that provides a client interface for connecting to a MongoDB server.

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. Download and Install the Mongodb Driver, Mongodb Shell and Eclipse on your Computer.
  2. Open the Mongodb Driver and Shell from your command prompt.
  3. Create a new Maven Project then update the dependency and Mongodb driver version in pom.xml.
  4. Next create a new (MongoDbPush) Java Class file from src/main/java.
  5. Copy the Code and Paste it into your Java class file.
  6. Save the file and right click on the code you will get the Run As option.
  7. Here, select 1 Java Application to Run the Code.
  8. You will get the output in the Console.
  9. We can get all the database collections in the Mongodb Shell as well. (Refer Preview of the output)


I hope you found this useful. I have added the 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

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

  • Eclipse IDE for Java Developers - 2023-03
  • Mongo Driver - 6.0.5 version.
  • mongosh -version - 1.8.0


With the help of this code we can able to Insert Array into a Collection using MongoClient in Java. This process also facilities an easy-to-use, hassle-free method to create a hands-on working version of code which would help us to Insert Array into a Collection using MongoClient in Java.

Support