CRUD Operations with MongoDB in Android Development

Daniel Kioko
TheCodr
Published in
3 min readJun 25, 2020

MongoDB Data Operations, written in Java.

Photo by Anete Lūsiņa on Unsplash

Being able to manipulate data is essential for most, if not every software developed. Even though many types databases work differently from each other, they still carry out the same major and most important tasks that is; creating, finding, updating and deleting data.

In this tutorial, I’ll cover how we can perform these four functions from MongoDB on Android Development:

  1. Find & Read Documents
  2. Create & Upload Documents
  3. Update Documents
  4. Deleting Documents

Find Documents 🔍

We’ll begin with finding documents since this operation come’s first before updating or deleting any specific data. We can find all documents from a database collection using the ‘collection.find()’ action. Specific documents can be found by defining a filter.

Document filter = new Document()
.append("_id", new Document().append("$exists", true));

RemoteFindIterable findResults = itemsCollection
.find(filter)

Create & Upload Documents 📤

Let’s assume you’re creating a social media app. To upload a post, we’d have to upload a data object containing information such as the picture URL, the caption, and maybe the date it was posted. We’d then define the Document item as shown below:

Document post = new Document()
.append("_id": qwizy001)
.append("imageURL", "https://unsplash.com/photos/4P0E3zcs_Nc")
.append("caption", "It's Crazy Cold Here")
.append("date", "1-1-2020"));

Once we’ve gathered all the information for the post, we can upload it to a collection in the database using the ‘collection.insertOne()’ action.

final Task <RemoteInsertOneResult> insertTask = newsFeedCollection.insertOne(post);insertTask.addOnCompleteListener(new OnCompleteListener <RemoteInsertOneResult> () {
@Override
public void onComplete(@NonNull
Task <RemoteInsertOneResult> task) {
if (task.isSuccessful()) {
Log.d("app", String.format("Uploaded!",
} else {
Log.e("app", "failed with error: ", task.getException());
}
}
});

Update Documents 🛠

Let’s assume we didn't upload a good enough caption for the post. We’ll have to find it, change the caption, then update the post on the database.

Document filter = new Document().append("_id", "qwizy001");
Document update = new Document().append("$set",
new Document()
.append("caption", "Helsinki's a cool place ❄️ 😎"));

For this we’d use the ‘collection.updateOne()’ action.

final Task<RemoteUpdateResult> updateTask =
newsFeedCollection.updateOne(filter, update);
updateTask.addOnCompleteListener(new OnCompleteListener <RemoteUpdateResult> () {
@Override
public void onComplete(@NonNull Task <RemoteUpdateResult> task) {
if (task.isSuccessful()) {
("app", String.format("Updated!"));
} else {
Log.e("app", "failed to update document with: ", task.getException());
}
}
});

If we wanted to update multiple posts, we’d update them using ‘collection.updateMany()’ action, and our ‘update’ variable would change to use ‘$mul’ instead of ‘$set

Document update = new Document().append("$mul", new Document().append("caption", "Helsinki's a cool place ❄️ 😎"));

Deleting Documents 🚮

Finally, we’d probably want to remove that post — maybe it’s not getting attention at all. We’d use the ‘collection.deleteOne()’ action to delete one item and ‘collection.deleteMany()’ action to delete multiple items.

Document filter = new Document().append("_id", "qwizy001");

final Task<RemoteDeleteResult> deleteTask = newsFeedCollection.deleteOne(filter);
deleteTask.addOnCompleteListener(new OnCompleteListener <RemoteDeleteResult> () {
@Override
public void onComplete(@NonNull Task <RemoteDeleteResult> task) {
if (task.isSuccessful()) {
Log.d("app", String.format("Deleted!"));
} else {
Log.e("app", "failed with error: ", task.getException());
}
}
});

That’s all! These are the four major operations, but there’s a lot more you can do with MongoDB

Feel free to let me know your thoughts. Happy coding! 🌟

--

--