5. mongod (launch server)
mongo (launch client)
mongorestore (load a db into mongo)
use database (within client, use spceific db)
db.collection.findOne();
6. Download/extract mongodb files
Either update Path to include bin folder or navigate to bin folder …
Create folder for data …
> md data -> md datadb (remember where you created this folder)
> mongod --dbpath c:datadb (default path onWindows)
▪ Now the mongodb server will be running (unless there is a problem)
From another command shell launch client: > mongo
▪ Now the mongodb shell will be running
▪ Try the following commands:
▪ show databases
▪ db
▪ show collections
7. Create - Insert
Read - Find
Update - Update
Delete - Remove
Everything is a method/API, not as SQL syntax
Valid: db.names.find()
Invalid: slect * from names
8. javascript interpreter
> for (i=0;i<3;i++) print("hello");
> help
> help keys
auto complete with tab
> z = {"a":1}
> z.a
> z["a"]
> x={a:1}; y="a"; x[y]++; print(x.a); // output is 2
10. > doc = {name: "Brady", age: 38, team: "Patriots"}
If players collection doesn’t exist, it will create one
db.players.insert(doc)
db.players.find()
"_id" is a unique id created by the database; immutable
> db.players.findOne() // random document
> db.players.remove({}) // remove all objects in collection
> db.players.delete() // remove the entire collection
11.
12. > db.players.findOne()
> db.players.findOne("name": "Brady")
> db.players.findOne({"name":"Brady", {"_id": false})
> db.players.findOne({"name":"Brady", {"_id": false, "name": true})
> db.players.find().pretty() // well-formatted
> db.players.count("name" : "Brady") // Count of records
> db.players.find({"name":"Brady", "age": 38}).pretty()
> db.players.find({"age": {$gt:30} }).pretty() // greater than 30
> db.players.find({"age": {$lt:40} }).pretty() // less than 40
> db.players.find({"age": {$gte:30, $lte:40}).pretty() // between 30
and 40
14. > db.players.find({"city": {$exists: true}})
> db.players.find({"city": {$exists: false}})
> db.players.find({"name": {$type: 2}}) // BSONTypes Numbers
docs.mongodb.org/manual/reference/bson-types/
// find all players with a "w" in the name key
> db.players.find({name: {$regex: "w"}}, {"_id":false, "name":true})
// find all players with names ending in "n"
> db.players.find({name: {$regex: "n$"}}, {"_id":false, "name":true})
// find all players with names that start with "b"
> db.players.find({name: {$regex: "^b"}}, {"_id":false, "name":true})
15. // find players that have age of 38 OR have a city
> db.players.find({$or: [{"age":38}, {"city": {$exists:true}}]})
// find players that have age 38 AND name equals "Brady"
> db.players.find({$and [{age:38}, {name:"Brady"}]})
// same as … a bit more efficient
> db.players.find({age:38, name:"Brady"})
//What about this?Think about javascript behavior!!
> db.players.find({age:38, age:40})
21. Combines Update/Insert
Excellent use case when you don't know if a document already
exists
> db.players.update({name:"Zahid"}, {$set: {age:30, team:
"Patriots"}}, {upsert: true} )
> db.players.find({name:"Zahid"}).pretty()
{
"_id" : ObjectId("55ca7b04f971f0ee874cf2af"),
"name" : "Zahid",
"age" : 30,
"team" : "Patriots"
}
22. {} empty document matches every document in collection
db.players.update({}, {$set : {newcol:10}})
Above statement will only update one document (the first
one)
To add newcol to all documents, use the multi option
db.players.update({}, {$set : {newcol:10}}, {multi: true})
Concurrency issues
Transactions are not isolated
If 10000 updates, possible that 2 different reads could get different
results
23. db.players.remove( {name: "brady"})
db.players.remove({}) // no need for multi option
db.players.drop() // drop the entire collection; more efficient
24. > db.players.ensureIndex({name:1}, {unique:true}) // ensure
unique index on name
> db.players.ensureIndex({name:1, age:1}) // compound index
on name and age
> db.players.getIndexes() // retrieves a list of all indexes on
players collections
> db.players.getIndexSize() // number of bytes allocated to
indexes
> db.players.reIndex()
27. > db.grades.findOne()
{
"_id" : ObjectId("50906d7fa3c412bb040eb577"),
"student_id" : 0,
"type" : "exam",
"score" : 54.6535436362647
}
// sql: selectTop 1 student_id _id, avg(score) average from grades group by student_id order by avg(score) desc
> db.grades.aggregate(
{'$group':{'_id':'$student_id', 'average':{$avg:'$score'}}},
{'$sort':{'average':-1}},
{'$limit':1})
// select student_id _id, min(score) min from grades where score >= 65 group by student_id order by min(score)
> db.grades.aggregate([
{ $match : { score : {$gte : 65 } } },
{ '$group': {'_id':'$student_id', 'min': { $min:'$score'} } },
{ '$sort': { 'min': 1 } } ] );
28. $bit - performs bitwise AND, OR, and XOR updates on integer values
$mod - performs a modulo operation on the value of a field
$not - returns documents that do not match query expression
$nor - returns documents that fail to match both clauses (as in "neither/nor")
Geospatial methods like $geoWithin, $geoIntersects, $near, $nearSphere
$hint - forces the query optimizer to use specific index
db.collection.find().explain() // retrieve query execution plan
$maxTimeMS - specifies maximum time for execution of query
$natural - sort documents by natural order (ordering of documents internally
within database)
$project - reshapes each document in the stream (adding new fields or removing
fields)
$cmp, $eq, $gt, $gte, $lt, $lte, $ne (equality operators)