Import Data to MongoDB From JSON File Using Java
Import Data to MongoDB from JSON File Using Java
MongoDB is a NoSQL Database that stores data in a document-oriented format, and provides support for dynamic queries and indexing. This makes it a popular choice for web developers who need to store and manage large amounts of data quickly and reliably. In this article, we’ll look at how to import data from a JSON file into MongoDB using Java.
What Is a JSON File?
JSON stands for JavaScript Object Notation, and is a text-based open standard designed for exchanging data. It can be used to store and exchange data between systems and applications. JSON files are typically composed of key-value pairs and have an .json file extension.
How to Import Data from a JSON File to MongoDB with Java
In order to import data from a JSON file to MongoDB, we first need to have a valid JSON file. Once we have our JSON file, we can begin our import process. Here are the steps we’ll need to take:
- Create a MongoClient object
- Specify the data source
- Load the JSON file into a String
- Use the JsonParser class to parse the JSON string
- Use the MongoCollection class to insert the parsed data into MongoDB
Example Code for Importing Data from a JSON File to MongoDB with Java
Now that we know the steps involved in importing data from a JSON file to MongoDB with Java, let’s look at an example of how to do it. We’ll use the following JSON file as the source for our data import:
{ "firstName": "John", "lastName": "Doe", "age": 32, "address": { "streetAddress": "123 Main St.", "city": "New York", "state": "NY", "postalCode": "10001" }, "phoneNumbers": [ { "type": "home", "number": "123-456-7890" }, { "type": "work", "number": "098-765-4321" } ] }
Here’s the code we’ll need to write in order to import data from this JSON file to MongoDB:
import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import org.bson.Document; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; MongoClient mongo = new MongoClient(); String jsonData = FileUtils.readFileToString(new File("file.json")); JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(jsonData); Document doc = Document.parse(jsonObject.toString()); MongoCollection coll = mongo.getDatabase("myDB").getCollection("myColl"); coll.insertOne(doc);
We first create a MongoClient object which is used to connect to the MongoDB database. Then we load our JSON file into a String and use the JsonParser class to parse the JSON string. Finally, we use the MongoCollection class to insert the parsed data into MongoDB.
Conclusion
In this article, we looked at how to import data from a JSON file to MongoDB using Java. We walked through the steps involved in the process and then looked at an example of how to do it. With these steps in hand, you should now be able to quickly and easily import data to MongoDB from a JSON file using Java.