How to use Mongodb
What is Mongodb
Mongodb is an open-source document oriented database developed by Mongodb.Inc. It is classified as a NoSQL database. It is widely used as document database in microservice projects.
How to install Mongodb
Mongodb has a lot of good tools for us to put our database on cloud. I don’t really know about it. Therefore, I installed mongodb-atlas
at first. However, this is not mongodb running on locally. It contains several shell tools and a project called atlas
to create a cluster on your mongodb cloud.
If you wanna deploy your database on cloud, you can install mongodb-atlas
and setup your mongodb atlas.
1 | brew install mongodb-atlas |
If you prefer to run mongodb locally, you should install mongodb-community@6.0 instead. For more comprehensive and detailed information, you can read this guide Install Mongodb Community Edition.
Use Mongodb in shell
It’s very necessary to know how to CRUD in mongodb at first.
We have a database called use sample_mflix
in this tutorial. You can use show dbs
to show all databases. show collections
can list all collections in your selected(used) database.
Create
Insert one record.
1 | use sample_mflix |
Insert many records.
1 | use sample_mflix |
Then we can use db.collection_name.find()
method to find records we added before.
Read
Read all records.
1 | db.movies.find() |
Specify Conditions.
1 | db.movies.find( { "title": "The Favourite" } ) |
Update
Update a single record.
1 | db.movies.updateOne( { title: "Tag" }, |
Update several records.
1 | db.listingsAndReviews.updateMany( |
Replace all content except id.
1 | db.accounts.replaceOne( |
Delete
Delete all.
1 | db.movies.deleteMany({}) |
Delete all match some condition.
1 | db.movies.deleteMany( { title: "Titanic" } ) |
Delete only one match some condition.
1 | db.movies.deleteOne( { cast: "Brad Pitt" } ) |
About this Post
This post is written by Chen Li, licensed under CC BY-NC 4.0.