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:
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.
Creating documents
To add a document to a collection, we use the insert() method of the collection.
Retrieving documents
To retrieve documents from a collection, we can create a query and then iterate through it with a cursor.
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.
Updating documents
To update an object, we first have to get the object from the collection then we save it back into the collection.
Deleting Documents
Finally, to delete a document or set of documents, we use the remove method of the collection.
From http://www.davidsalter.co.uk/1/post/2011/05/basic-java-crud-operations-with-mongodb.html
Comments