Insert Array into a Collection using MongoClient in Java
by vsasikalabe Updated: Mar 31, 2023
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.
- insert() – Inserts a single document or multiple documents into a collection.
- insertOne() – Inserts a single document into a collection.
- 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.
Instructions
Follow the steps carefully to get the output easily.
- Download and Install the Mongodb Driver, Mongodb Shell and Eclipse on your Computer.
- Open the Mongodb Driver and Shell from your command prompt.
- Create a new Maven Project then update the dependency and Mongodb driver version in pom.xml.
- Next create a new (MongoDbPush) Java Class file from src/main/java.
- Copy the Code and Paste it into your Java class file.
- Save the file and right click on the code you will get the Run As option.
- Here, select 1 Java Application to Run the Code.
- You will get the output in the Console.
- 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.