MongoDB Snip it

To create a database

use <database name>

use school #creates a database name school instance

output

'switched to db school'

create a collection

db.<collection name>

db.staff #creates a collection name "staff" instance

db.staff.insertOne({"name": "Balogun Rukayat", "dateOfEmployment":"01/01/2020", "qualification":"B.Ed", "salary":30000, "type":"teaching staff"}) #creates a record in the collection name, staff

Multiple Inserts

The code below creates multiple records in the collection name , staff

db.staff.insertMany([{name: "Fasasi Taiwo", dateOfEmployment:"21/02/2020", qualification:"B.Tech", salary:20000, type:"non-teaching staff"}, {name: "Fashola Babatunde", dateOfEmployment:"2/03/2021", qualification:"B.Sc", salary:23000, type:"non-teaching staff"}, {name: "Kaka Jumoke", dateOfEmployment:"31/04/2010", qualification:"B.Art", salary:20000, type:"non-teaching staff"}, {name: "Olagunju Samson", dateOfEmployment:"3/3/2014", qualification:"B.Sc", salary:21000, type:"teaching staff"})

Read records from collection

db.staff.find() #displays all the records in staff collection and limit to the first 20 records

db.staff.find({type:"teaching staff"}) #returns all records with type:teaching staff

db.staff.find({type:"teaching staff"}).count() #returns the counts of all records that are of type:teaching staff

db.staff.find({salary:21000}) #returns all the records that have salary equal to 21000

#Update record(s) in a collection

db.staff.updateOne({_id: ObjectId("6310b825083e2c3b43237d5c")}, {$set:{qualification:"B.Tech"}}) #updates the value of qualification in the id specified to "B.Tech"

db.staff.updateOne({ _id: ObjectId("6310b7fb083e2c3b43237d5b")}, {$set:{dateOfEmployment:"30/04/2010"}}) #updates the record of the specified id to the date passed


db.staff.updateMany({salary:30000}, {$inc:{salary:2000}}) #updates the value of the record with salary , 30000 by 2000 returns 32000

db.staff.update({_id: ObjectId("6310b759083e2c3b43237d58")}, {$push:{contact:"0702345678"}}) #adds contact as the last input

db.staff.update({_id: ObjectId("6310b759083e2c3b43237d58")}, {$pop:{contact:-1}}) #removes the last item in the array