Build a MongoDB database of people and phone numbers using the mongo shell and some Bash scripts.
The tasks are described HERE .
First Name | Last Name | Nickname | Phone Number |
---|---|---|---|
Tommy | Rot | 666-555-8888 | |
Judy | Zed | Z | 626-555-9999 |
Piccolo | Pete | 626-555-1234 | |
Arleen | Pete | Buttercup |
#!/bin/bash mongo --quiet <<EOF show dbs db = db.getSiblingDB('phonedb'); db.phones.insert({ 'firstname' : 'Tommy', 'lastname' : 'Rot', 'phonenumber': '666-555-8888' }); db.phones.insert({ 'firstname' : 'Judy', 'lastname' : 'Zed', 'phonenumber': '626-555-9999', 'nickname' : 'Z'}); db.phones.insert({ 'firstname' : 'Piccolo', 'lastname' : 'Pete', 'phonenumber': '626-555-1234'}); db.phones.insert({ 'firstname' : 'Arleen', 'lastname' : 'Pete', 'nickname' : 'Buttercup'}); EOF
$ mongo >
> cls
> show dbs
> db
> use phonedb > show collections
> use phonedb
> use phonedb > db.dropDatabase()
> use phonedb > db.createCollection{"phones")
> use phonedb > db.phones.drop()
Insert a document > db.phones.insert({ first_name:"John",last_name:"Doe" } Insert multiple documents > db.phones.insert( [{ first_name:"Steven",last_name:"Smith" }, {....},{....} ])
find all documents > db.phones.find() find all documents and pretty print > db.phones.find().pretty() find all Marys > db.phones({firstname: "Mary"}) find with or > db.phones({$or: [{first_name:"Mary"},{age:45}] ) find less than, greater than > db.phones.find({age:{$gt:40}}) <-- age > 40 > db.phones.find({age:{$lt:21}}) <-- age < 21 $lte less that or equal $gte greater than or equal find memberships > dn.phones.find({memberships:"mem1" }) find documents without an age field > db.phones.find({ age: { $exists: true, $ne: null }}).pretty()
Find and just replace a field > db.phones.update({first_name:"John" <-- find Johns Doe last_name:"Doe"}, {$set:{age:45}} <-- just replace/set age modify but if not found insert it > db.phones.update({first_name:"Mary"}, {first_name:"Mary",Last_name:"Samson"}, {upsert: true}); find a Johns and replace/set their gender > db.phones.update({first_name:"John"}, {first_name:"John", last_name:"Doe", gender:"male"}) find a Johns Does and only replace/set the first one found > db.phones.update({first_name:"John",last_name:"Doe"}, {$set:{gender:"male"}})
> db.phones.update({first_name:"John", last_name:"Doe"}, {$unset{age:1}}})
> use phonedb delete everybody in the collection > db.phones.remove({}) delete all (first_name = Mary) > db.phones.remove({first_name:"Mary"}) delete the first mary found > db.phones.remove({first_name:"Mary"},{justone:true})