How to do CRUD operations in MongoDB (Ubuntu 20.04)

Louis SanchezAugust 15th 2021, 8:24

CRUD operations create, read, update, and delete documents.

Follow these steps to store and retrieve data with MongoDB

Step 1 : Open a shell to interact with the Mongo server


Step 2 : To create and start using a new database, type use dbname. Since schemas in MongoDB are dynamic, you do not need to create a database before using it:

use testdb

Step 3 : Let’s insert our first document:


Step 4 : To view the created database and collection, use the following commands:

show dbs

show collections

Step 5 : You can also insert multiple values for a key

db.users.insert({'name':'root','uid':1010, 'gid':[1010, 1000, 1111]})

Step 6 : Check whether a document is successfully inserted


Step 7 : To get a single record, use findOne():


Step 8 : To update an existing record, use the update command as follows:

db.users.update({name:'ubuntu'}, {$set:{uid:2222}})

Step 9 : To remove a record, use the remove command. This will remove all records with a name equal to ubuntu


Step 10 : To drop an entire collection, use the drop() command


Step 11 : To drop a database, use the dropDatabase() command