MongoDB Shell Commands

MongoDB CRUD shell command and operations

MongoDB Shell Commands

1. Get List of database
Command: show dbs

2. Get current database name
Command: db

3. Switch to another database
Command: use database_name
Example: use testdb

4. Create new table
command: db.createCollection('table_name')
Example: db.createCollection(‘tbl_user’)

5. Get List of table
Command: show collections

6. Insert record in table (
command : db.table_name.insert( {key:"value",....} )
Example: db.tbl_user.insert( { name: “Sam”, status: “Active”,email:”sam01@gmail.com” } )

7. Insert multiple records in table (
command : db.table_name.insertMany( {key:"value",....},{key:"value",....},...)
Example: db.tbl_user.insertMany( [{ name: “Sam”, status: “Active”,email:”sam01@gmail.com” },{ name: “Anddy”, status: “Active”,email:”anddy01@gmail.com” }] )

8. List record of table
Command: db.table_name.find() Or db.table_name.find().pretty()
Example: db.tbl_user.find() Or db.tbl_user.find().pretty()

9. Update record
Command: db.table_name.update({key:"value"}, {$set: {key:"new_value"}})
Example: db.tbl_user.update({name:”Sam”}, {$set: {email:”sam.mobio@gmail.com”}})

10. Delete Record
Command: db.table_name.deleteOne({key:"value"})
Example: db.tbl_user.deleteOne({name:”Sam”})

11. Delete multiple record for given condition
Command: db.table_name.deleteMany({key:"value"})
Example: Command: db.tbl_user.deleteMany({email:”sam.mobio@gmail.com”})

12. Search Record in table
Command: db.table_name.find({key:"value"}).pretty()
Example: db.tbl_user.find({name:”Sam”}).pretty()

 

Reference :

https://docs.mongodb.com/manual/mongo/

https://docs.mongodb.com/manual/reference/mongo-shell/