SlideShare a Scribd company logo
Zahid Mian
Part of the Brown-bag Series
 Schema-less
 Document DB (don't thinkWord Document)
 Document is a JSON object
 Supports Indexes
 Scalable
 Doesn't Support "traditional" Joins
 Doesn't SupportTransactions (not ACID-compliant)
 Version 3.0.5 (in this doc)
 http://docs.mongodb.org/manual/
 https://www.mongodb.org/downloads
 Dictionaries and Arrays
 {}
 {"fruits": ["apple", "pear", "peach"]}
 {name: "Adam Smith"}
 {numbers: [7,2,3,8]}
 {name: "Adam Smith", hobbies: [hobby: "Econ",
hobby:"Tennis"]}
 Formal Representation: http://json.org/
RDBMS SQL MONGODB
database database
table collection
index index
row document
column field
joining N/A
 mongod (launch server)
 mongo (launch client)
 mongorestore (load a db into mongo)
 use database (within client, use spceific db)
 db.collection.findOne();
 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
 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
 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
 Binary Specification (bsonspec.org)
 Allows storage of extended datatypes
 Date,Timestamp, Double, Integer, etc.
 > obj = {
a:1,
b: ISODate("2015-03-21T17:41:55.325Z", c:},
c: NumberLong(555389),
d: Boolean(true)
}
 > 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
 > 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
> db.players.find({"name": {$lt: "C"}},
{"_id":false, "name":true})
{ "name" : "Brady" }
{ "name" : "B" }
> db.players.find({"name": {$gt: "B"}}, {"_id":false,
"name":true})
{ "name" : "Brady" }
{ "name" : "brady" }
{ "name" : "Cano" }
{ "name" : "b" }
{ "name" : "brown" }
> db.players.find({"name": {$gt: "b"}}, {"_id":false,
"name":true})
{ "name" : "brady" }
{ "name" : "brown" }
> db.players.find({}, {"_id":false, "name":true})
{ "name" : "Brady" }
{ "name" : "brady" }
{ "name" : "Cano" }
{ "name" : "B" }
{ "name" : "b" }
{ "name" : "brown" }
 > 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})
 // 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})
 > db.accounts.find()
 {"name" : "Adam", "favs" : [ "ice cream", "pretzels", "chips" ] }
 {"name" : "Mike", "favs" : [ "beer", "chips" ] }
 {"name" : "Sam", "favs" : "chips" }
 > db.accounts.find({favs:"chips"})
 > db.accounts.find({favs:"chips", name: {$gte : "M"}})
 > db.accounts.find({favs: {$all:["chips", "pretzels"]}})
 > db.accounts.find({favs: {$any: ["beer", "pretzels"]}})
> db.users.find().pretty()
{
"_id" :
ObjectId("55ca69a88b9e931abe0295db"),
"name" : "Adam",
"email" : {
"work" : "abc@dddd1.com",
"personal" : "abc2@dkjdkd.com"
}
}
{
"_id" : ObjectId("55ca6a318b9e931abe0295dc"),
"name" : "zahid",
"email" : {
"work" : "abc@eeeee2.com",
"personal" : "abc3@dkjdkd.com"
}
}
> db.users.find({"email.work": {$regex:"dddd"
}}).pretty()
{
"_id" : ObjectId("55ca69a88b9e931abe0295db"),
"name" : "Adam",
"email" : {
"work" : "abc@dddd1.com",
"personal" : "abc2@dkjdkd.com"
}
}
 > cur = db.players.find();
 > cur.hasNext()
 > cur.next()
 > while (cur.hasNext()) printjson(cur.next());
 > cur.limit(5); // nothing is executed until cursor is read
 > cur.sort( {name: -l} ); // negative lexicographical sort
 > cur.sort( {name: -l} ).limit(5); // chaining methods
 > cur.sort( {name: -l} ).limit(5).skip(1) // first sort, then limit,
then skip
> db.players.find({name:"brady"})
{ "_id" : ObjectId("55ca58bf8b9e931abe0295d4"), "name" : "brady", "age" : 40, "team" : "Patriots" }
// update all player documents where name equals "brady" (set age to 42, team to "Broncos")
> db.players.update({name: "brady"}, {age: 42, team:"Broncos"} )
> db.players.find({team:"Broncos"})
{ "_id" : ObjectId("55ca58bf8b9e931abe0295d4"), "age" : 42, "team" : "Broncos" } // name is gone!
> db.players.update({team: "Broncos"}, {name: "brady", age: 42, team:"Patriots"} ) // put name back
> db.players.find({name:"brady"})
{ "_id" : ObjectId("55ca58bf8b9e931abe0295d4"), "name" : "brady", "age" : 42, "team" : "Patriots" }
> db.players.update({name:"brady"},{$set: {age:50}})
> db.players.find({name:"brady"})
{ "_id" : ObjectId("55ca58bf8b9e931abe0295d4"), "name" : "brady", "age" : 50, "team" : "Patriots" }
> db.players.update({name:"brady"},{$unset: {age:1}}
> db.players.find({name:"brady"})
{ "_id" : ObjectId("55ca58bf8b9e931abe0295d4"), "name" : "brady", "team" : "Patriots" }
> db.arrays.insert( {_id: 0, a: [1,2,3,4]})
> db.arrays.find()
{ "_id" : 0, "a" : [ 1, 2, 3, 4 ] }
> db.arrays.update({_id:0}, {$set: {"a.2": 5}})
> db.arrays.find()
{ "_id" : 0, "a" : [ 1, 2, 5, 4 ] }
> db.arrays.update({_id:0}, {$push: {a: 6}})
> db.arrays.find()
{ "_id" : 0, "a" : [ 1, 2, 5, 4, 6 ] }
> db.arrays.update({_id:0}, {$pop: {a: 1}})
> db.arrays.find()
{ "_id" : 0, "a" : [ 1, 2, 5, 4 ] }
> db.arrays.update({_id:0}, {$pop: {a: -1}})
> db.arrays.find()
{ "_id" : 0, "a" : [ 2, 5, 4 ] }
> db.arrays.update({_id:0}, {$pushAll: {a:
[7,8,9]}})
> db.arrays.find()
{ "_id" : 0, "a" : [ 2, 5, 4, 7, 8, 9 ] }
> db.arrays.update({_id:0}, {$pull: {a: 5}})
> db.arrays.update({_id:0}, {$pull: {a: 5}})
> db.arrays.find()
{ "_id" : 0, "a" : [ 2, 4, 7, 8, 9 ] }
> db.arrays.update({_id:0}, {$pullAll: {a:
[8,9]}})
> db.arrays.find()
{ "_id" : 0, "a" : [ 2, 4, 7 ] }
> db.arrays.update({_id:0}, {$addToSet: {a:
3}})
> db.arrays.find()
{ "_id" : 0, "a" : [ 2, 4, 7, 3 ] }
 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"
}
 {} 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
 db.players.remove( {name: "brady"})
 db.players.remove({}) // no need for multi option
 db.players.drop() // drop the entire collection; more efficient
 > 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()
 count
 distinct
 group
> db.records.group( {
key: { a: 1 },
cond: { a: { $lt: 3 } },
reduce: function(cur, result) {
result.count += cur.count },
initial: { count: 0 }
} )
> 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 } } ] );
 $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)
MongoD Essentials

More Related Content

What's hot

MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB
 
Advanced MongoDB #1
Advanced MongoDB #1Advanced MongoDB #1
Advanced MongoDB #1
Takahiro Inoue
 
Storing tree structures with MongoDB
Storing tree structures with MongoDBStoring tree structures with MongoDB
Storing tree structures with MongoDB
Vyacheslav
 
Mapping Flatland: Using MongoDB for an MMO Crossword Game (GDC Online 2011)
Mapping Flatland: Using MongoDB for an MMO Crossword Game (GDC Online 2011)Mapping Flatland: Using MongoDB for an MMO Crossword Game (GDC Online 2011)
Mapping Flatland: Using MongoDB for an MMO Crossword Game (GDC Online 2011)
Grant Goodale
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Webinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible SchemasWebinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible Schemas
MongoDB
 
Strongly Typed Languages and Flexible Schemas
Strongly Typed Languages and Flexible SchemasStrongly Typed Languages and Flexible Schemas
Strongly Typed Languages and Flexible Schemas
Norberto Leite
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)MongoSF
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() Output
MongoDB
 
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
영욱 김
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter Bootstrap
Howard Lewis Ship
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB
antoinegirbal
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query OptimizationMongoDB
 
How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)
How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)
How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)
Paul Richards
 
Building DSLs with Groovy
Building DSLs with GroovyBuilding DSLs with Groovy
Building DSLs with Groovy
Sten Anderson
 
Building a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and JavaBuilding a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and Java
antoinegirbal
 

What's hot (18)

MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDBMongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
MongoDB .local London 2019: Tips and Tricks++ for Querying and Indexing MongoDB
 
Advanced MongoDB #1
Advanced MongoDB #1Advanced MongoDB #1
Advanced MongoDB #1
 
Storing tree structures with MongoDB
Storing tree structures with MongoDBStoring tree structures with MongoDB
Storing tree structures with MongoDB
 
php plus mysql
php plus mysqlphp plus mysql
php plus mysql
 
Mapping Flatland: Using MongoDB for an MMO Crossword Game (GDC Online 2011)
Mapping Flatland: Using MongoDB for an MMO Crossword Game (GDC Online 2011)Mapping Flatland: Using MongoDB for an MMO Crossword Game (GDC Online 2011)
Mapping Flatland: Using MongoDB for an MMO Crossword Game (GDC Online 2011)
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Webinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible SchemasWebinar: Strongly Typed Languages and Flexible Schemas
Webinar: Strongly Typed Languages and Flexible Schemas
 
Strongly Typed Languages and Flexible Schemas
Strongly Typed Languages and Flexible SchemasStrongly Typed Languages and Flexible Schemas
Strongly Typed Languages and Flexible Schemas
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() Output
 
Mongo db presentation
Mongo db presentationMongo db presentation
Mongo db presentation
 
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
4시간만에 따라해보는 Windows 10 앱 개발 샘플코드
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter Bootstrap
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
 
How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)
How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)
How to win $10m - analysing DOTA2 data in R (Sheffield R Users Group - May)
 
Building DSLs with Groovy
Building DSLs with GroovyBuilding DSLs with Groovy
Building DSLs with Groovy
 
Building a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and JavaBuilding a Scalable Inbox System with MongoDB and Java
Building a Scalable Inbox System with MongoDB and Java
 

Viewers also liked

Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
Claudio Montoya
 
Mongo db
Mongo dbMongo db
Mongo db
Edmilson Neto
 
Connecting NodeJS & MongoDB
Connecting NodeJS & MongoDBConnecting NodeJS & MongoDB
Connecting NodeJS & MongoDB
Enoch Joshua
 
MongoDB for Beginners
MongoDB for BeginnersMongoDB for Beginners
MongoDB for Beginners
Enoch Joshua
 
Intro to NoSQL and MongoDB
Intro to NoSQL and MongoDBIntro to NoSQL and MongoDB
Intro to NoSQL and MongoDBDATAVERSITY
 
Mongo db
Mongo dbMongo db
Mongo db
Akshay Mathur
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDB
Alex Sharp
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
Ravi Teja
 

Viewers also liked (11)

Pdf almas
Pdf almasPdf almas
Pdf almas
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
Mongo db
Mongo dbMongo db
Mongo db
 
Connecting NodeJS & MongoDB
Connecting NodeJS & MongoDBConnecting NodeJS & MongoDB
Connecting NodeJS & MongoDB
 
MongoDB for Beginners
MongoDB for BeginnersMongoDB for Beginners
MongoDB for Beginners
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Intro to NoSQL and MongoDB
Intro to NoSQL and MongoDBIntro to NoSQL and MongoDB
Intro to NoSQL and MongoDB
 
Mongo db
Mongo dbMongo db
Mongo db
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Intro To MongoDB
Intro To MongoDBIntro To MongoDB
Intro To MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 

Similar to MongoD Essentials

MongoDB
MongoDB MongoDB
Webinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev TeamsWebinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev Teams
MongoDB
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Groupkchodorow
 
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 LinkMongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
MongoDB
 
Mongo db for c# developers
Mongo db for c# developersMongo db for c# developers
Mongo db for c# developers
Simon Elliston Ball
 
NDC London 2013 - Mongo db for c# developers
NDC London 2013 - Mongo db for c# developersNDC London 2013 - Mongo db for c# developers
NDC London 2013 - Mongo db for c# developers
Simon Elliston Ball
 
Mongo DB 102
Mongo DB 102Mongo DB 102
Mongo DB 102
Abhijeet Vaikar
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
Jainul Musani
 
Schema Design with MongoDB
Schema Design with MongoDBSchema Design with MongoDB
Schema Design with MongoDB
rogerbodamer
 
MongoDB全機能解説2
MongoDB全機能解説2MongoDB全機能解説2
MongoDB全機能解説2Takahiro Inoue
 
Mongo db basic installation
Mongo db basic installationMongo db basic installation
Mongo db basic installation
Kishor Parkhe
 
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB
 
2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade
Johannes Hoppe
 
Tips and Tricks for Avoiding Common Query Pitfalls
Tips and Tricks for Avoiding Common Query PitfallsTips and Tricks for Avoiding Common Query Pitfalls
Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data ModelingDATAVERSITY
 
Schema Design
Schema DesignSchema Design
Schema Design
MongoDB
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
Mike Dirolf
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: Keynote
MongoDB
 
Spark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSpark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. Jyotiska
Sigmoid
 

Similar to MongoD Essentials (20)

MongoDB
MongoDB MongoDB
MongoDB
 
Webinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev TeamsWebinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev Teams
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
 
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 LinkMongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
MongoDB World 2019: Using Client Side Encryption in MongoDB 4.2 Link
 
Mongo db for c# developers
Mongo db for c# developersMongo db for c# developers
Mongo db for c# developers
 
NDC London 2013 - Mongo db for c# developers
NDC London 2013 - Mongo db for c# developersNDC London 2013 - Mongo db for c# developers
NDC London 2013 - Mongo db for c# developers
 
Latinoware
LatinowareLatinoware
Latinoware
 
Mongo DB 102
Mongo DB 102Mongo DB 102
Mongo DB 102
 
MongoDB-SESSION03
MongoDB-SESSION03MongoDB-SESSION03
MongoDB-SESSION03
 
Schema Design with MongoDB
Schema Design with MongoDBSchema Design with MongoDB
Schema Design with MongoDB
 
MongoDB全機能解説2
MongoDB全機能解説2MongoDB全機能解説2
MongoDB全機能解説2
 
Mongo db basic installation
Mongo db basic installationMongo db basic installation
Mongo db basic installation
 
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
MongoDB .local Houston 2019: Using Client Side Encryption in MongoDB 4.2
 
2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade
 
Tips and Tricks for Avoiding Common Query Pitfalls
Tips and Tricks for Avoiding Common Query PitfallsTips and Tricks for Avoiding Common Query Pitfalls
Tips and Tricks for Avoiding Common Query Pitfalls
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling
 
Schema Design
Schema DesignSchema Design
Schema Design
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: Keynote
 
Spark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSpark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. Jyotiska
 

More from zahid-mian

Mongodb Aggregation Pipeline
Mongodb Aggregation PipelineMongodb Aggregation Pipeline
Mongodb Aggregation Pipeline
zahid-mian
 
Hadoop Technologies
Hadoop TechnologiesHadoop Technologies
Hadoop Technologies
zahid-mian
 
Intro to modern cryptography
Intro to modern cryptographyIntro to modern cryptography
Intro to modern cryptography
zahid-mian
 
Hadoop M/R Pig Hive
Hadoop M/R Pig HiveHadoop M/R Pig Hive
Hadoop M/R Pig Hive
zahid-mian
 
NoSQL Databases
NoSQL DatabasesNoSQL Databases
NoSQL Databases
zahid-mian
 
Statistics101: Numerical Measures
Statistics101: Numerical MeasuresStatistics101: Numerical Measures
Statistics101: Numerical Measures
zahid-mian
 
Amazon SimpleDB
Amazon SimpleDBAmazon SimpleDB
Amazon SimpleDB
zahid-mian
 
C# 6 New Features
C# 6 New FeaturesC# 6 New Features
C# 6 New Features
zahid-mian
 
Introduction to d3js (and SVG)
Introduction to d3js (and SVG)Introduction to d3js (and SVG)
Introduction to d3js (and SVG)
zahid-mian
 

More from zahid-mian (9)

Mongodb Aggregation Pipeline
Mongodb Aggregation PipelineMongodb Aggregation Pipeline
Mongodb Aggregation Pipeline
 
Hadoop Technologies
Hadoop TechnologiesHadoop Technologies
Hadoop Technologies
 
Intro to modern cryptography
Intro to modern cryptographyIntro to modern cryptography
Intro to modern cryptography
 
Hadoop M/R Pig Hive
Hadoop M/R Pig HiveHadoop M/R Pig Hive
Hadoop M/R Pig Hive
 
NoSQL Databases
NoSQL DatabasesNoSQL Databases
NoSQL Databases
 
Statistics101: Numerical Measures
Statistics101: Numerical MeasuresStatistics101: Numerical Measures
Statistics101: Numerical Measures
 
Amazon SimpleDB
Amazon SimpleDBAmazon SimpleDB
Amazon SimpleDB
 
C# 6 New Features
C# 6 New FeaturesC# 6 New Features
C# 6 New Features
 
Introduction to d3js (and SVG)
Introduction to d3js (and SVG)Introduction to d3js (and SVG)
Introduction to d3js (and SVG)
 

Recently uploaded

Jpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization SampleJpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization Sample
James Polillo
 
一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单
ewymefz
 
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
John Andrews
 
tapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive datatapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive data
theahmadsaood
 
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape ReportSOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar
 
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
ewymefz
 
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdfCh03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
haila53
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
nscud
 
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
axoqas
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
yhkoc
 
一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单
enxupq
 
standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
ArpitMalhotra16
 
一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单
enxupq
 
Innovative Methods in Media and Communication Research by Sebastian Kubitschk...
Innovative Methods in Media and Communication Research by Sebastian Kubitschk...Innovative Methods in Media and Communication Research by Sebastian Kubitschk...
Innovative Methods in Media and Communication Research by Sebastian Kubitschk...
correoyaya
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year Rebound
Oppotus
 
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
vcaxypu
 
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
ewymefz
 
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
axoqas
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
ewymefz
 
一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单
ewymefz
 

Recently uploaded (20)

Jpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization SampleJpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization Sample
 
一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单
 
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
Chatty Kathy - UNC Bootcamp Final Project Presentation - Final Version - 5.23...
 
tapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive datatapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive data
 
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape ReportSOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape Report
 
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
 
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdfCh03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
 
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
 
一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单一比一原版(YU毕业证)约克大学毕业证成绩单
一比一原版(YU毕业证)约克大学毕业证成绩单
 
standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
 
一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单
 
Innovative Methods in Media and Communication Research by Sebastian Kubitschk...
Innovative Methods in Media and Communication Research by Sebastian Kubitschk...Innovative Methods in Media and Communication Research by Sebastian Kubitschk...
Innovative Methods in Media and Communication Research by Sebastian Kubitschk...
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year Rebound
 
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
 
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
 
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
 
一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单
 

MongoD Essentials

  • 1. Zahid Mian Part of the Brown-bag Series
  • 2.  Schema-less  Document DB (don't thinkWord Document)  Document is a JSON object  Supports Indexes  Scalable  Doesn't Support "traditional" Joins  Doesn't SupportTransactions (not ACID-compliant)  Version 3.0.5 (in this doc)  http://docs.mongodb.org/manual/  https://www.mongodb.org/downloads
  • 3.  Dictionaries and Arrays  {}  {"fruits": ["apple", "pear", "peach"]}  {name: "Adam Smith"}  {numbers: [7,2,3,8]}  {name: "Adam Smith", hobbies: [hobby: "Econ", hobby:"Tennis"]}  Formal Representation: http://json.org/
  • 4. RDBMS SQL MONGODB database database table collection index index row document column field joining N/A
  • 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
  • 9.  Binary Specification (bsonspec.org)  Allows storage of extended datatypes  Date,Timestamp, Double, Integer, etc.  > obj = { a:1, b: ISODate("2015-03-21T17:41:55.325Z", c:}, c: NumberLong(555389), d: Boolean(true) }
  • 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
  • 13. > db.players.find({"name": {$lt: "C"}}, {"_id":false, "name":true}) { "name" : "Brady" } { "name" : "B" } > db.players.find({"name": {$gt: "B"}}, {"_id":false, "name":true}) { "name" : "Brady" } { "name" : "brady" } { "name" : "Cano" } { "name" : "b" } { "name" : "brown" } > db.players.find({"name": {$gt: "b"}}, {"_id":false, "name":true}) { "name" : "brady" } { "name" : "brown" } > db.players.find({}, {"_id":false, "name":true}) { "name" : "Brady" } { "name" : "brady" } { "name" : "Cano" } { "name" : "B" } { "name" : "b" } { "name" : "brown" }
  • 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})
  • 16.  > db.accounts.find()  {"name" : "Adam", "favs" : [ "ice cream", "pretzels", "chips" ] }  {"name" : "Mike", "favs" : [ "beer", "chips" ] }  {"name" : "Sam", "favs" : "chips" }  > db.accounts.find({favs:"chips"})  > db.accounts.find({favs:"chips", name: {$gte : "M"}})  > db.accounts.find({favs: {$all:["chips", "pretzels"]}})  > db.accounts.find({favs: {$any: ["beer", "pretzels"]}})
  • 17. > db.users.find().pretty() { "_id" : ObjectId("55ca69a88b9e931abe0295db"), "name" : "Adam", "email" : { "work" : "abc@dddd1.com", "personal" : "abc2@dkjdkd.com" } } { "_id" : ObjectId("55ca6a318b9e931abe0295dc"), "name" : "zahid", "email" : { "work" : "abc@eeeee2.com", "personal" : "abc3@dkjdkd.com" } } > db.users.find({"email.work": {$regex:"dddd" }}).pretty() { "_id" : ObjectId("55ca69a88b9e931abe0295db"), "name" : "Adam", "email" : { "work" : "abc@dddd1.com", "personal" : "abc2@dkjdkd.com" } }
  • 18.  > cur = db.players.find();  > cur.hasNext()  > cur.next()  > while (cur.hasNext()) printjson(cur.next());  > cur.limit(5); // nothing is executed until cursor is read  > cur.sort( {name: -l} ); // negative lexicographical sort  > cur.sort( {name: -l} ).limit(5); // chaining methods  > cur.sort( {name: -l} ).limit(5).skip(1) // first sort, then limit, then skip
  • 19. > db.players.find({name:"brady"}) { "_id" : ObjectId("55ca58bf8b9e931abe0295d4"), "name" : "brady", "age" : 40, "team" : "Patriots" } // update all player documents where name equals "brady" (set age to 42, team to "Broncos") > db.players.update({name: "brady"}, {age: 42, team:"Broncos"} ) > db.players.find({team:"Broncos"}) { "_id" : ObjectId("55ca58bf8b9e931abe0295d4"), "age" : 42, "team" : "Broncos" } // name is gone! > db.players.update({team: "Broncos"}, {name: "brady", age: 42, team:"Patriots"} ) // put name back > db.players.find({name:"brady"}) { "_id" : ObjectId("55ca58bf8b9e931abe0295d4"), "name" : "brady", "age" : 42, "team" : "Patriots" } > db.players.update({name:"brady"},{$set: {age:50}}) > db.players.find({name:"brady"}) { "_id" : ObjectId("55ca58bf8b9e931abe0295d4"), "name" : "brady", "age" : 50, "team" : "Patriots" } > db.players.update({name:"brady"},{$unset: {age:1}} > db.players.find({name:"brady"}) { "_id" : ObjectId("55ca58bf8b9e931abe0295d4"), "name" : "brady", "team" : "Patriots" }
  • 20. > db.arrays.insert( {_id: 0, a: [1,2,3,4]}) > db.arrays.find() { "_id" : 0, "a" : [ 1, 2, 3, 4 ] } > db.arrays.update({_id:0}, {$set: {"a.2": 5}}) > db.arrays.find() { "_id" : 0, "a" : [ 1, 2, 5, 4 ] } > db.arrays.update({_id:0}, {$push: {a: 6}}) > db.arrays.find() { "_id" : 0, "a" : [ 1, 2, 5, 4, 6 ] } > db.arrays.update({_id:0}, {$pop: {a: 1}}) > db.arrays.find() { "_id" : 0, "a" : [ 1, 2, 5, 4 ] } > db.arrays.update({_id:0}, {$pop: {a: -1}}) > db.arrays.find() { "_id" : 0, "a" : [ 2, 5, 4 ] } > db.arrays.update({_id:0}, {$pushAll: {a: [7,8,9]}}) > db.arrays.find() { "_id" : 0, "a" : [ 2, 5, 4, 7, 8, 9 ] } > db.arrays.update({_id:0}, {$pull: {a: 5}}) > db.arrays.update({_id:0}, {$pull: {a: 5}}) > db.arrays.find() { "_id" : 0, "a" : [ 2, 4, 7, 8, 9 ] } > db.arrays.update({_id:0}, {$pullAll: {a: [8,9]}}) > db.arrays.find() { "_id" : 0, "a" : [ 2, 4, 7 ] } > db.arrays.update({_id:0}, {$addToSet: {a: 3}}) > db.arrays.find() { "_id" : 0, "a" : [ 2, 4, 7, 3 ] }
  • 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()
  • 25.  count  distinct  group > db.records.group( { key: { a: 1 }, cond: { a: { $lt: 3 } }, reduce: function(cur, result) { result.count += cur.count }, initial: { count: 0 } } )
  • 26.
  • 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)