DEV Community

Cover image for Beginners MongoDB Cheat-Sheet
Shubham Athawane
Shubham Athawane

Posted on • Updated on

Beginners MongoDB Cheat-Sheet

What is MongoDB ?

MongoDB is a document-oriented NoSQL database used for high valume data storage instead of using table and rows as in the traditional relational databses, MongoDB makes use of collections and documents

Then Question arises What is documents and Collections ?

Documents : Consist of key-value pairs which are the basic unit of the data in MongoDB.

Collections : Contain sets of documents and functions which is the equivalent of relational database tables


1.Enlist available databases

 Show db 
Enter fullscreen mode Exit fullscreen mode

2 . To Create a new DB

 use db-name
Enter fullscreen mode Exit fullscreen mode

3 . See your current working directry

  db
Enter fullscreen mode Exit fullscreen mode

4 . Delete Database

db.mydb.drop()
Enter fullscreen mode Exit fullscreen mode

5 . Create User

-> db.createUser({
    user:'admin',
    pws:'root',
    roles:["readWrite", "dbAdmin"]  
})
Enter fullscreen mode Exit fullscreen mode

6 . Creating Collections

-> db.createCollection('customers');
Enter fullscreen mode Exit fullscreen mode

7 . Showing Collections

-> show collections
Enter fullscreen mode Exit fullscreen mode

8 . Inserting values into collections

-> db.customers.insert({first_name:"shubham", last_name:"Athawane"});
Enter fullscreen mode Exit fullscreen mode

9 . View Collection Records

-> db.customers.find();
//And
-> db.customers.find().pretty();
//Note: pretty() will show you result in json formate
Enter fullscreen mode Exit fullscreen mode

10 . Add new Document in Collections

->  db.customers.insert([{"first_name":"Virat", "last_name":"Kohli"},
 {"first_name":"Taylor", "last_name":"Swift"}])
// And -> $set, $inc, $unset
-> db.customers.update({first_name:"Glen"}, {$set:{age:45}})
Enter fullscreen mode Exit fullscreen mode

11 . Rename Document

-> db.customers.update({first_name:"Virat"}, {$rename:{"age":"old"}})
Enter fullscreen mode Exit fullscreen mode

12 . Remove document

-> db.customers.remove({first_name:"Joe"})
Enter fullscreen mode Exit fullscreen mode

13 . find the matching

-> db.customers.findOne({first_name:"Joe"}) 
Enter fullscreen mode Exit fullscreen mode

14 . Count Rows

-> db.customers.count()

Enter fullscreen mode Exit fullscreen mode

15 . This is Less than/Greater than/ Less than or Eq/Greater than or Eq operators

db.customers.find({age: {$lt: 90}})
db.customers.find({age: {$lte: 90}})
db.customers.find({age: {$gt: 90}})
db.customers.find({age: {$gte: 90}})
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
capcom6 profile image
capcom6

Typo in 9: db.customers.instert must be db.customers.insert

Collapse
 
shubhamathawane profile image
Shubham Athawane

Yes! Corrected ! Thank You 😚