I hope this example can be a good start for us to learn more about MongoDB.
The Java class above is our first example of how to use the MongoDB Java Driver to access and read a document from the MongoDB database. This is the JSON document that we’ve store in our peopledb in the MongoDB database.If you run this code, you will get the following output printed on the screen.(Objects.requireNonNull(document).toJson()) Gets a single document / object from this collection.ĭocument document = collection.find().first() MongoCollection collection = database.getCollection("persons") Gets the persons collections from the database. MongoDatabase database = client.getDatabase("peopledb") Gets the peopledb from the MongoDB instance. Creates a new instance of MongoDBClient and connect to localhost
And this is the full code snippet for the MongoDBHelloWorld class.Type in the class name MongoDBHelloWorld, and press OK button.Right-click on this package and choose New, Java Class to create a new class. We create our class under the package.Now we are going to read it using the MongoDB Java Driver in our Java application. Rapidly create and deploy powerful Java applications that integrate wi. If you are following the last post about installing and running MongoDB that I have mention in the beginning of this article you know that we have a peopledb and persons collections in our MongoDB database. After configuring the Maven, we are now ready to create a simple program to find a single collection from the MongoDB database. IntelliJ IDEA will download all the required dependency files from the Maven Central repository if they are not available in you local Maven repository. Whether youre developing on a local or on-premise MongoDB installation or going cloud-first with MongoDB Atlas, the MongoDB Java Driver and surrounding ecosystem make it a snap to integrate MongoDB into your development process. Add the following dependency configuration to the pom.xml. Java and MongoDB are two of the most popular technologies for software development, so its no surprise that they work well together.To use the MongoDB Java Driver in our Java application, the first thing we need to do is to add the dependency to MongoDB Java Driver in our pom.xml file.Maven Project Structure Editing the pom.xml File