How to insert a document in mongodb in java - example

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

Octocat The code examples are taken from the Free-Programming-Books-Importer, 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:


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’ll be adding 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(category);//all links have at least one category (fall under an ### element)
if(subCategory != null) {
System.out.println("tags : " + tags);
document.append("tags", tags);

Insert the document

Check if the collection contains already the codingmark based on location, or else add the document to the collection with the help of insertOne method:

Document bookmark = bookmarksCollection.find(eq("location", location)).first();
    System.out.println("*********************** Bookmark already present *********************** ");
} else {

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.

Octocat Source code for this example is available on Github

Adrian Matei

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

Free Programming Books are now on

We're happy to announce that we've reached and surpassed our goal of 1 Mb #codingmarks, by importing the books from the Free-Programming-Books project Continue reading