Basic Querying in MongoDB
Basic Querying in MongoDB
LearnTracker:LifeLongLearningwithMOOCs
EDWARD'SLECTURENOTES:
Morenotesathttp://tanguay.info/learntracker(http://tanguay.info/learntracker)
COURSE
MongoDBforNode.jsDevelopers
AndrewErlichson,MongoDBUniversity
https://university.mongodb.com/courses/10gen/M101JS/2014_June/about
(https://university.mongodb.com/courses/10gen/M101JS/2014_June/about)
COURSELECTURE
BasicQueryinginMongoDB
NotestakenonJune11,2014byEdwardTanguay
CRUD/Mongo/SQLterminology
Create=Insert=INSERT
Read=Find=SELECT
Update=Update=UPDATE
Delete=Remove=DELETE
MongoDB'sCRUDoperationexistasmethods/functionsinprogramminglanguageAPIs
MongoDBdoesnothaveaseparatelanguagethatneedstobeembeddedasstringsinside
codethatoperatesonMongoDB
asadeveloper,youmanipulatethedatabaseusingmethodsonobjects,similartoaobject
mappingwithRDBMS
thismakesdatabaseI/OwithMongoDBrelativelypleasantforprogrammers
theMongoshell
theMongoshellisaninteractiveJavaScriptinterpreter
payattentiontotheversionnumberwhenyoulogin
youcantypeinjavascriptatthecommandline
(http://tanguay.info/learntracker/customImages/itemTypes/javascript_at_command_line.jpg)
http://tanguay.info/learntracker/page/lectureNotesPrint?lectureNotesItemIdCode=basicquerying
1/5
1/12/2015
LearnTracker:LifeLongLearningwithMOOCs
uparrowretrievespreviouscommands
ctrlatofrontofline
builtinhelpers
help
helpkeys
commandcompletion
basicjavascriptvariableassignment
(http://tanguay.info/learntracker/customImages/itemTypes/javascript_defining.jpg)
BSON
fundamentalrecordtypeisanesteddictionaryofkey/valueassociations
javascriptobjects,becausetheyareindictionary/JSONform,canbesaveddirectlyinto
thedatabase
JSONwasinspiredbythesyntaxofJavaScript
MondoDBdoesnotusethisstringysyntax
http://bsonspec.orgBSONspecBSONisbinaryJSON,hasdatatypesthatgobeyond
JSON,e.g.datetime,32and64bitintegertype,etc.
intheshellweuseJavaScriptandwecanforcethetypesofnumbers
NumberInt(1)
NumberLong(1)
butbecarefulwithlanguagessuchasJavaScriptorPerlwhichcan'trepresentallofthe
http://tanguay.info/learntracker/page/lectureNotesPrint?lectureNotesItemIdCode=basicquerying
2/5
1/12/2015
LearnTracker:LifeLongLearningwithMOOCs
typesthatBSONcanrepresent
newDate()orISODate(...)
soyoucanfaithlyhandleallofthedatathatcomesoutofthedatabasebycastingitlike
this:
(http://tanguay.info/learntracker/customImages/itemTypes/castingtypes.jpg)
insertingdocs
theshellhasavariablenameddbwhichisahandletothecurrentdatabase
collectionsarepropertiesofthedatabase,e.g.db.people.insert(doc)
(http://tanguay.info/learntracker/customImages/itemTypes/how_to_insert.jpg)
whenyouinsertadocument,itgetsauniquefield"_id"
differentfromotherdatabases,theprimarykeyisimmutable
youcouldsimilatechangingtheidbyremovingadocument,andinsertingitagainsoit
getsanotherid
_idistheprimarykey
_idisalwaysObjectIdmadeupofdate,machine,processidoncomputer,anda
counter,sotheseideasaregloballyunique
ifyoudon'tinsertan_id,thenonewillbegeneratedforyou
findingdocuments
db.fruit.find() willfindall
db.people.findOne({name:"Jones"})
thequeryispresentedtotheserverintheformofastructureddocument
thesecondargumentallowsyoutospecifywhichfieldsyouwanttogetback,trueorfalse
(http://tanguay.info/learntracker/customImages/itemTypes/second_argument.jpg)
http://tanguay.info/learntracker/page/lectureNotesPrint?lectureNotesItemIdCode=basicquerying
3/5
1/12/2015
LearnTracker:LifeLongLearningwithMOOCs
_id isincludedbydefault
find
filldatabasesowecandosomequeries:
(http://tanguay.info/learntracker/customImages/itemTypes/fill_database.jpg)
db.people.find() toseethemall
type it iteratethroughtheresults
shelliskeepingtheseresultsopen
cursorisontheserver,willclearitin10minutes
dp.people.find().pretty() toseeresultsformatted
whenmultiplefieldsaregiveninthefirstparametersoffind(),thenitassumesAND
thesearecalled"querybyexample"queries
queryoperators
db.scores.find({score:{$gt:95,$lte:95}) (greaterthan,lessthanorequal)
>,<etc.canalsobeappliedtostrings
currentlysortsasciibetically
futureversionsshouldhavebettersupport
allcomparisonoperationsarestronglytyped
ifyoufilterbylessthan"A",youwillnotgetnumbers
generally,youshouldnotmixtypesinonenamedfield,e.g.store42inaname
herethethirditemwillnotworksincecomparisonsarecasesensitive
(http://tanguay.info/learntracker/customImages/itemTypes/case_sensitive.jpg)
queryingonwhetherfieldexists
http://tanguay.info/learntracker/page/lectureNotesPrint?lectureNotesItemIdCode=basicquerying
4/5
1/12/2015
LearnTracker:LifeLongLearningwithMOOCs
(http://tanguay.info/learntracker/customImages/itemTypes/find_if_exists.jpg)
youcancheckforatype,usetheBSONspecifications,sostring=2:
do.people.find({name:{$type:2}})
youcanalsouseregexs:
allnamesthatendwith"e"
(http://tanguay.info/learntracker/customImages/itemTypes/regex.jpg)
http://tanguay.info/learntracker/page/lectureNotesPrint?lectureNotesItemIdCode=basicquerying
5/5