0% found this document useful (0 votes)
2 views3 pages

mongoDB_cheat_sheet

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

mongoDB_cheat_sheet

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

mongoDB

Cheat Sheet
//@bekbrace
//Friday, 18th June, 2021
//mongoDB basic commands and queries

//To show all databases


show dbs

//To switch(choose) a database


use sampleDatabase

//Show the colelctions in a database


show collections

//Creating a new database


use newDB
show dbs

//To show which database we are currently in


db

//To create collections


db.createCollection('clients')

//Insert a document
db.clients.insert({
id:0,
company: "lasosta",
address: " 23 lost st NYC",
overdue_invoices: 24,
products : ['coffee', 'sugar'],
date : Date(),
contacts : {
name: "Jim Neil",
position:"owner",
phone: 5550011,
},})
//To query the data
db.clients.find()

//To delete a document


db.clients.remove({id:0})

//to insert multiple documents


db.clients.insertMany ([
{
id : 0,
company: "lasosta",
address : "23 lost street-NY",
overdue_invoices : 20,
products: ['sugar', 'coffee'],
creation_date : Date(),
},
{
id : 1,
company: "vanilla factory",
address : "23 great street-CA",
overdue_invoices : 21,
products: ['milk', 'vanilla'],
creation_date : Date(),
},{
id : 2,
company: "john & sons",
address : "23 found street-TX",
overdue_invoices : 22,
products: ['books', 'magazines'],
creation_date : Date(),
},
])
//choose a document based ona criteria
//similar to //SELECT * FROM CLIENTS where overdue_invoice = 21 in SQL
db.clients.find({overdue_invoices:21})

//counting
db.clients.find({overdue_invoices:20}).count()
//sort ( ascending 1 - descending -1 )
db.clients.find().sort({id:1})

//Updating - safe way


db.clients.update({id:2},
{
$set:{
overdue_invoices: 40,
importer: "James Co. Ltd",
}
})

db.clients.find()

//Incrementing
db.clients.update({id:1}, {$inc: {overdue_invoices:1}})
db.clients.find()

//renaming
db.clients.update({id:1}, {$rename: {company: 'legal_name'}})

db.clients.find()

//update array in id 0
db.clients.update({id:0},
{ $set : {
products :['sugar', 'coffee'],
}
})
db.clients.find()

You might also like