MongoDB

## Install MongoDB **Install mongoDB** ``` brew tap MongoDB/brew brew install mongodb-community ``` **Check services and uninstall mongodb** ``` brew services list brew uninstall mongodb-community ``` **Start services** ``` brew services start mongodb-community brew services stop mongodb-community ``` **Connect to the shell** ``` mongosh ``` **Link** [mongodb for mac](https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/) ## Use of MongoDB **show dbs** ``` test> show dbs admin 40.00 KiB config 60.00 KiB local 72.00 KiB ``` **Enter a database** ``` test> use shopDB switched to db shopDB shopDB> show collections products ``` **To see which database you are in** ``` > db ``` **Insert** ``` shopDB> db.products.insertOne({_id: 1, name: "Pen", price:1.20}) { acknowledged: true, insertedId: 1 } shopDB> show collections products shopDB> db.products.insertOne({_id: 2, name: "Pencil", price:0.80}) { acknowledged: true, insertedId: 2 } shopDB> db.products.find() [ { _id: 1, name: 'Pen', price: 1.2 }, { _id: 2, name: 'Pencil', price: 0.8 } ] ``` ``` shopDB> db.products.insertOne({ ... _id: 2, ... name: "Pencil", ... price: 0.80, ... stock: 12, ... reviews: [ ... { ... authorName: "James", ... rating: 4, ... review: "Great" ... }, ... { ... authorName: "Jono", ... rating: 5, ... review: "The best pencil I've used in my life." ... } ... ] ... }) { acknowledged: true, insertedId: 2 } ``` **Find** ``` shopDB> db.products.find({name: "Pencil"}) [ { _id: 2, name: 'Pencil', price: 0.8 } ] shopDB> db.products.find({price: {$gt:1}}) [ { _id: 1, name: 'Pen', price: 1.2 } ] shopDB> db.products.find({_id:1}, {name:1}) [ { _id: 1, name: 'Pen' } ] shopDB> db.products.find({_id:1}, {name:1, _id:0}) [ { name: 'Pen' } ] ``` **Update** ``` shopDB> db.products.updateOne({_id:1}, {$set:{stock: 32}}) { acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 } shopDB> db.products.find() [ { _id: 1, name: 'Pen', price: 1.2, stock: 32 }, { _id: 2, name: 'Pencil', price: 0.8 } ] shopDB> db.products.updateOne({_id:2}, {$set: {stock: 12}}) { acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 } shopDB> db.products.find() [ { _id: 1, name: 'Pen', price: 1.2, stock: 32 }, { _id: 2, name: 'Pencil', price: 0.8, stock: 12 } ] ``` **Delete** ``` shopDB> db.products.deleteOne({_id: 2}) { acknowledged: true, deletedCount: 1 } shopDB> db.products.find() [ { _id: 1, name: 'Pen', price: 1.2, stock: 32 } ] ```