You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# if not present then created else selected
use databasename
# list current db name
db
# list all database
show dbs
# Adding a document in current db
db.movie.insert({
"name":"xyz"
})
Deleting a Database
use databasename
db.dropDatabase()
Creating a Collection
db.createCollection(name, options) # options is like a document itself, where we tell size etc# example db.createCollection("mycollection")# example db.createCollection("mycol", {capped:true, autoIndexId:true, size:6142800, max:10000})
showcollections # shows the created collection# MongoDB automatically creates a collection when we add some document to a not created collection# example: db/magicalCollection.insert({"name":"I love LP"})
Dropping a database
db.mycollection.drop()
Datatypes in MongoDB
String
Integer
Boolean
Double
Min/Max keys
Arrays
Timestamp
Object
Null
Symbol
Date
Object Id
Binary data
Code
Regular expression
Inserting a document
db.collectionname.insert({"name":"Kush"}) # Inserting a single document
db.collectionname.insert([{...}, {...}, {...}]) # Inserting multiple documents
Querying Documents
db.collectionname.find() # returns everything
db.collectionname.find({"number":9588}) # returns all, and iter is returned not arraydb.collectionname.find({"number":9588}).pretty() # A prettier output
db.collectionname.findOne({"number":9588}) # returns only 1
Updating, Deleting, Projection, Sorting and Limiting Documents in MongoDB
You can use update or save
# Updating
db.mycollection.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Overview'}})
db.mycollection.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Overview'}}, {multi:true}) # Multiple updates## Deleting
db.mycollection.remove({'title':'MongoDB Overview'}) # justOne=1 to only delete one# Projection - retrive only some of the key:value pair, which are marked as 1
db.mycol.find({}, {"title":1, _id:0}) # list all but only title# Limiting Recordsdb.mycollection.find().limit(100)
# Sorting Documents - 1 for asc, -1 for decdb.mycollection.find().sort({'likes':1}) # here likes is a key