Tutorial

How To Create, Retrieve, Update, and Delete Records in MongoDB

Published on December 12, 2019
Default avatar

By Andrew Ulm

How To Create, Retrieve, Update, and Delete Records in MongoDB

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Introduction

MongoDB is a free and open-source NoSQL document database used commonly in modern web applications. In this short tutorial, you’ll explore how to work with data in MongoDB. You’ll create, retrieve, update, and delete records.

Prerequisites

To complete this tutorial you’ll need MongoDB installed, which you can do by following How To Install MongoDB on Ubuntu 18.04.

Creating a Database

On the server running MongoDB, type mongo to open up a connection to the database:

  1. mongo

Once you see the > symbol, you’re ready to create your first database and start adding records.

Let’s create a personal database to store some data about users.

Our first command use userdb creates a new database with the name of “userdb” you can put whatever name you want in the format use <databasename>.

  1. use userdb

You can verify the database you are currently using with the db command, which in our case returns “userdb”:

  1. db
Output
userdb

Now that your database has been created, you can create some JSON-structured documents to store data in your database.

Execute the following command to insert some data into your database:

  1. db.people.insert({ name: "Andrew", age: 33, hobbies: ["Coding", "Gaming", "Cooking"], hungry: false})

You’ll get the WriteResult notification letting you know your insertion was successful:

Output
WriteResult({ "nInserted" : 1 })

You can use many data-types, including strings, numbers, arrays, and boolean values. The Key doesn’t need to have the double quotation marks.

Retrieving Data

Once you have data in your collection, you can start to search and filter that data out using .find(<parameters>)

To verify that your data has been added to the “people” document, use the find() syntax. Execute this command in the MongoDB console:

  1. db.people.find()

This command shows all data that are currently associated with the “people” document.

Output
{ "_id" : ObjectId("5c08c98f3d828385a2162d94"), "name" : "Andrew", "age" : 33, "hobbies" : [ "Coding", "Gaming", "Cooking" ], "hungry" : false }

If you want to turn this into pretty JSON format, use .pretty() after .find() :

  1. db.people.find().pretty()
Output
{ "_id" : ObjectId("5c08c98f3d828385a2162d94"), "name" : "Andrew", "age" : 33, "hobbies" : [ "Coding", "Gaming", "Cooking" ], "hungry" : false }

When you add a new record, that Mongo will automatically create an _id key for you to reference at a later time.

Try to add more data and then we’ll work on modifying and searching the data.

  1. db.people.insert({ name: "Riley", age: 3, hobbies: ["Sleeping", "Barking", "Snuggles"], hungry: true})
  2. db.people.insert({ name: "You", age: 30, hobbies: ["Coding", "Reading DigitalOcean Articles", "Creating Droplets"], hungry: true})

For instance, if I wanted to find only the records of those who are hungry:

  1. db.people.find({ hungry: true }).pretty()
Output
{ "_id" : ObjectId("5c08cbea3d828385a2162d95"), "name" : "Riley", "age" : 3, "hobbies" : [ "Sleeping", "Barking", "Snuggles" ], "hungry" : true } { "_id" : ObjectId("5c08cc2e3d828385a2162d96"), "name" : "You", "age" : 30, "hobbies" : [ "Coding", "Reading DigitalOcean Articles", "Creating Droplets" ], "hungry" : true }

Or by specific hobbies:

  1. db.people.find({ hobbies: "Coding" }).pretty()
Output
{ "_id" : ObjectId("5c08c98f3d828385a2162d94"), "name" : "Andrew", "age" : 33, "hobbies" : [ "Coding", "Gaming", "Cooking" ], "hungry" : false } { "_id" : ObjectId("5c08cc2e3d828385a2162d96"), "name" : "You", "age" : 30, "hobbies" : [ "Coding", "Reading DigitalOcean Articles", "Creating Droplets" ], "hungry" : true }

Updating Data

To modify your data, use the .update() function. but first let’s look at our data to see what we want to change:

  1. db.people.find().pretty()
Output
{ "_id" : ObjectId("5c08c98f3d828385a2162d94"), "name" : "Andrew", "age" : 33, "hobbies" : [ "Coding", "Gaming", "Cooking" ], "hungry" : false } { "_id" : ObjectId("5c08cbea3d828385a2162d95"), "name" : "Riley", "age" : 3, "hobbies" : [ "Sleeping", "Barking", "Snuggles" ], "hungry" : true } { "_id" : ObjectId("5c08cc2e3d828385a2162d96"), "name" : "You", "age" : 30, "hobbies" : [ "Coding", "Reading DigitalOcean Articles", "Creating Droplets" ], "hungry" : true }

Modify the name of the third record like this:

  1. db.people.update({ name: "You" }, {$set: { name: "Sammy" }})

The first part of your statement specifies what you are searching for to update, and the second part is the new value you want to set. You’ll notice with this command, there was 1 record match, and 1 record modified:

Output
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

If we now check that record with our newly set name:

  1. db.people.find({ name: "Sammy" }).pretty()
Output
{ "_id" : ObjectId("5c08cc2e3d828385a2162d96"), "name" : "Sammy", "age" : 30, "hobbies" : [ "Coding", "Reading DigitalOcean Articles", "Creating Droplets" ], "hungry" : true }

The name key value has been set to its new value of Sammy.

You can also push new hobbies to the array by using $push instead of $set :

  1. db.people.update({ name: "Sammy" }, {$push: { hobbies: "Typing furiously" }})
  2. db.people.find({ name: "Sammy" }).pretty()
Output
{ "_id" : ObjectId("5c08cc2e3d828385a2162d96"), "name" : "Sammy", "age" : 30, "hobbies" : [ "Coding", "Reading DigitalOcean Articles", "Creating Droplets", "Typing furiously" ], "hungry" : true }

Now let’s look at deleting data.

Deleting Data (D)

Remove data using the .remove() function. You can remove data in a couple of ways, but the safest way is to locate a record to delete by using the unique _id so that, for instance, you have multiple "Sammy" entries, removing by the name: "Sammy" would remove all of them. Let’s try this:

  1. db.people.remove({ _id: ObjectId("5c08cc2e3d828385a2162d96")})
Output
WriteResult({ "nRemoved" : 1 })
  1. db.people.find().pretty()
Output
{ "_id" : ObjectId("5c08c98f3d828385a2162d94"), "name" : "Andrew", "age" : 33, "hobbies" : [ "Coding", "Gaming", "Cooking" ], "hungry" : false } { "_id" : ObjectId("5c08cbea3d828385a2162d95"), "name" : "Riley", "age" : 3, "hobbies" : [ "Sleeping", "Barking", "Snuggles" ], "hungry" : true }

The "Sammy" entry has been removed safely, without affecting any other possible "Sammy" records if they were to exist. Try experimenting with this to see what else you can do.

Conclusion

After reading this article, you now have a basic understanding of how to create, retrieve, update, and delete records in a MongoDB database.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Andrew Ulm

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel