Objective: This segment introduces implementation of how to insert the JSON (JavaScript Object Notation) file documents into a collection in MongoDB using Java.
Prerequisites: MongoDB setup is installed and running in the background. Also, the project has been developed and executed in Eclipse IDE (Integrated Development Environment).
To run the following program, you need to download the MongoDB Java driver jar file Download MongoDB Java driver. Once downloaded, you can import the library by right-clicking on your project in Eclipse -> Properties -> Java Build Path -> Libraries -> Add External JARs...
Start MongoDB (running mongo.exe)
MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 4.2.3
> show dbs
DB 0.000GB
admin 0.000GB
config 0.000GB
local 0.000GB
> use DB
switched to db DB
> db.getCollectionNames()
[ "holders" ]
> db.holders.find().pretty()
>
Java MongoDB to insert the JSON file documents into a collection
In the following program, database and collection automatically get created. If database and collection already exist in MongoDB, then new documents will get inserted into an existing collection. Furthermore, we will be inserting documents into a holders collection using the JSON file, and once all the documents inserted, we will retrieve those using find() method.
Dear User, Thank you for visitng KodingWindow. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.