How to insert a document in mongodb in java - example


Dev-Bookmarks Logo

Save up to a workweek a year by efficiently managing your dev bookmarks, on www.bookmarks.dev. Share your favorites with the community and they will be published on Github - Star


This blog post presents a simple example showing how to insert a document in mongodb, in the Java language.

Octocat The code samples are taken from the Free-Programming-Books-Importer project, available on Github

Use MongoDB Java Driver

Add the java mongo driver to your class path, or if you use maven to the dependencies in your pom file:

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.2.2</version>
    </dependency>
    ......
</dependencies>

Prepare the Mongo Client

MongoClientURI connectionString = new MongoClientURI("mongodb://codingpedia:codingpedia@localhost:27017/codingpedia-bookmarks");
MongoClient mongoClient = new MongoClient(connectionString);

Select Mongo Database and Collection

Get the Mongo database:

MongoDatabase database = mongoClient.getDatabase("codingpedia-bookmarks");

A database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases.

Now we need to select the collection, where we add our newly created document:

MongoCollection<Document> bookmarksCollection = database.getCollection("bookmarks");

A collection is a grouping of MongoDB documents. A collection is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection have a similar or related purpose.

Prepare the document to be inserted

...
Document document = new Document();
String title = line.substring(line.indexOf("[")+1,line.indexOf("]"));
document.append("name", title);

Set<String> tags = new HashSet<>();
tags.add("free-programming-books");//all free programming books get this tag
tags.add(getFileNameWithoutExtension(fileName));
tags.add(category);//all links have at least one category (fall under an ### element)
if(subCategory != null) {
    tags.add(subCategory);
}
System.out.println("tags : " + tags);
document.append("tags", tags);

Insert the document

Check if the collection contains already the codingmark document based on location. Else add the document to the collection with the help of insertOne method:

Document bookmark = bookmarksCollection.find(eq("location", location)).first();
if(bookmark!=null){
    System.out.println("*********************** Bookmark already present *********************** ");
} else {
    bookmarksCollection.insertOne(document);
    numberOfInsertedBookmarks++;
}

A document is a record in a MongoDB collection and the basic unit of data in MongoDB. Documents are analogous to JSON objects but exist in the database in a more type-rich format known as BSON. See Documents for more information.

Octocat Source code for this example is available on Github

Adrian Matei

Adrian Matei
Life force expressing itself as a coding capable human being

New dev bookmarks in february 2019

Lots of exciting #DevBookmarks in february 2019. Keywords: api, architecture, arquillian, aws, bash, bootstrap, chai, cheatsheet, devops, diagram, dns, documentation, domain-driven-design, error-handling, facebook, favicon, ffmpeg, free-programming-books, functional-programming, gif, git, graph, html, html5, integration-testing, java, javascript, junit, jvm, kotlin, latex, linux, markdown, microservices, middleware, mocha, mongodb, monitoring, nginx, nodejs, oidc, online-tools, open-source, openid-connect, osx, pandoc, podcast, promise, reactive, reactive-programming, reactjs, redis, rest, rxjs, shell, spring, spring-boot, spring-cloud-gateway, spring-security, spring-webflux, sql, testing, tools, video-processing, visualization, web, websocket, windows and zuul Continue reading