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):