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.
To complete this tutorial you’ll need MongoDB installed, which you can do by following How To Install MongoDB on Ubuntu 18.04.
On the server running MongoDB, type mongo
to open up a connection to the database:
- 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>
.
- use userdb
You can verify the database you are currently using with the db
command, which in our case returns “userdb”:
- db
Outputuserdb
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:
- 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:
OutputWriteResult({ "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.
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:
- 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()
:
- 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.
- db.people.insert({ name: "Riley", age: 3, hobbies: ["Sleeping", "Barking", "Snuggles"], hungry: true})
- 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:
- 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:
- 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
}
To modify your data, use the .update()
function. but first let’s look at our data to see what we want to change:
- 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:
- 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:
OutputWriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
If we now check that record with our newly set name:
- 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
:
- db.people.update({ name: "Sammy" }, {$push: { hobbies: "Typing furiously" }})
- 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.
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:
- db.people.remove({ _id: ObjectId("5c08cc2e3d828385a2162d96")})
OutputWriteResult({ "nRemoved" : 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.
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.
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.
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!