DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • MongoDB to Couchbase for Developers, Part 1: Architecture
  • MongoDB to Couchbase: An Introduction to Developers and Experts
  • MongoDB With Spring Boot: A Simple CRUD
  • Manage Hierarchical Data in MongoDB With Spring

Trending

  • How To Use ChatGPT API in Python for Your Real-Time Data
  • Memory Management in Java: An Introduction
  • How To Optimize Feature Sets With Genetic Algorithms
  • Send Your Logs to Loki
  1. DZone
  2. Data Engineering
  3. Databases
  4. Basic Java CRUD Operations with MongoDB

Basic Java CRUD Operations with MongoDB

David Salter user avatar by
David Salter
·
May. 11, 11 · Interview
Like (0)
Save
Tweet
Share
33.35K Views

Join the DZone community and get the full member experience.

Join For Free

In this post I’d like to show how to perform basic CRUD operations against a MongoDB database using the Java driver.


For this post, lets assume that we have a todo database with a collection of todo items. Each item has a task and a priority.
In terms of JSON notation, an example item would look like:
{
  "_id" : { "$oid" : "4bffb75121eec88a67ff6ec8"} ,
  "task" : "Write Code" ,
  "priority" : "high"
}
Now that we have defined what we are storing in the database, lets have a look at how we connect to Mongo.

Connection to the database

To connect to a MongoDB database, we would use code similar to that below. In this code you can see that we are connecting to a database called todo and getting the collection called items. In MongoDB if neither of these items exist, they will be automatically created.
Mongo mongo = new Mongo();
DB db = mongo.getDB("todo");
DBCollection items = db.getCollection("items");

Creating documents

To add a document to a collection, we use the insert() method of the collection.
BasicDBObject doc1 = new BasicDBObject();
doc1.put("task", "Write Code");
doc1.put("priority", "high");
items.insert(doc1);

Retrieving documents

To retrieve documents from a collection, we can create a query and then iterate through it with a cursor.
BasicDBObject query = new BasicDBObject();
query.put("priority", "highest");
DBCursor cursor = items.find(query);
// Print out "highest" priority items
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

This query will find all the objects in the collection that have a priority of highest. If we wanted to get all of the items in the collection, we would create the cursor without a query as shown below.
DBCursor cursor = items.find();

Updating documents

To update an object, we first have to get the object from the collection then we save it back into the collection.
BasicDBObject findTestItemQuery = new BasicDBObject();
findTestItemQuery.put("task", "Test Code");
DBCursor testItemsCursor = items.find(findTestItemQuery);
if(testItemsCursor.hasNext()) {
    DBObject testCodeItem = testItemsCursor.next();
    testCodeItem.put("task", "Test and Review Code");
    items.save(testCodeItem);
}

Deleting Documents

Finally, to delete a document or set of documents, we use the remove method of the collection.
BasicDBObject deleteQuery = new BasicDBObject();
deleteQuery.put("priority", "highest");
DBCursor cursor = items.find(deleteQuery);
while (cursor.hasNext()) {
    DBObject item = cursor.next();
    items.remove(item);
}

 

From http://www.davidsalter.co.uk/1/post/2011/05/basic-java-crud-operations-with-mongodb.html

MongoDB Java (programming language) Database Document

Opinions expressed by DZone contributors are their own.

Related

  • MongoDB to Couchbase for Developers, Part 1: Architecture
  • MongoDB to Couchbase: An Introduction to Developers and Experts
  • MongoDB With Spring Boot: A Simple CRUD
  • Manage Hierarchical Data in MongoDB With Spring

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: