How to insert a document in mongodb in java - example


Dev-Bookmarks Logo

Bookmarking for Developers & Co with www.bookmarks.dev. Use our Add to Bookmarks.dev bookmarklet to your bookmarks toolbar for a seamless experience. 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

Subscribe to our newsletter for more code resources and news

Adrian Matei

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

Key takeaways when using Open API Specification 3 to document an ExpressJS API

Presents key points you should consider when using Open API to document an ExpressJS REST API Continue reading