How to do CRUD operations in MongoDB (Ubuntu 20.04)

Louis SanchezNovember 26th 2020, 11:07

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

mongo

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:

db.users.insert({'name':'ubuntu','uid':1001})

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

db.users.find()

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

db.users.findOne({uid:1010})

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

db.users.remove({'name':'ubuntu'})

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

db.users.drop()

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

db.dropDatabase()