mongodb crash course - niv dayan - github pagesnivdayan.github.io/mongo.pdf · starting mongodb...
TRANSCRIPT
MongoDB CrashCourse
ComputeFest
Niv Dayan
12 January, 2017
Installation
OSX: https://www.youtube.com/watch?v=G--uGbOFF9E(youmayneedtoadd“sudo”asaprefixtoeveryinstallationcommand)
Windows: https://www.youtube.com/watch?v=K_5mj3-_uJQ
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
StartingMongoDB
CommandstorunareinblueStartserver.Openterminalwindowandrun:
mkdir DBmongod --dbpath DB
Startclient.Opendifferentterminalandrun:mongo
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
Lookslikethis:
Serverwindow Clientwindow
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
CreateaCollection(inclient)
Createadatabaseentryvar customer={name:"bob",balance:100}db.customers.insert(customer)
Wenowhaveonecollectionofcustomersshowcollections
Inthecollection,wehaveonecustomerdb.customers.find()
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
PrettyPrinting
Printthingsnicelydb.customers.find().pretty()
NotethateachdocumentwithinacollectionhasauniqueIDthatiscreatedautomatically
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
Filtering
Createanothercustomervar customer2={name:"sara",balance:200}db.customers.insert(customer2)
Again,listallcustomers:db.customers.find().pretty()
ListcustomerscalledSaradb.customers.find({name:"sara"}).pretty()
Listcustomerswithbalancegreaterthan150db.customers.find({balance:{$gt:150}}).pretty()
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
UpdatingDocuments
Givebobasurnamedb.customers.update(
{name:"bob"},{$set:{surname:"Dylan"}})Add50toBob’saccount
db.customers.update({name:"bob"},{$inc :{balance:50}})
Checkoutcomedb.customers.find().pretty()
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
CopyingaDocument
CreateacopyofBobvar cust =db.customers.findOne({name:"bob"})
Printthesurnameofthecopycust["surname"]
Changethesurnameofthecopycust["surname"]="Marley"
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
SavingaCopytotheDatabase
Trytosavethecopyinthedatabase(won’twork)db.customers.insert(cust)
GenerateanewobjectIDvar o=ObjectId()
AssignthenewIDtothecopycust["_id"]=o
Nowtrytoinsertagaindb.customers.insert(cust)
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
Aggregation
Findsumofallaccountbalancesdb.customers.aggregate([{$group:{
_id:null,total:{$sum:"$balance"}}}])
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
Shutdownserver
Shutdowntheserverandquitclientuseadmindb.shutdownServer()exit
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE
Thanks!
13
INSTITUTEFORAPPLIEDCOMPUTATIONALSCIENCE