Last active
April 20, 2022 14:38
-
-
Save BekBrace/593dadb07b9751ef76aa076aaa4a5b02 to your computer and use it in GitHub Desktop.
MongoDB Cheat Sheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I used Datagrip in my crash course, but you can use the mongodb shell and you'll ge tthe same results. | |
//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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment