EDWARD'S LECTURE NOTES:
More notes at http://tanguay.info/learntracker
C O U R S E 
MongoDB for Node.js Developers
Andrew Erlichson, MongoDB University
https://university.mongodb.com/courses/10gen/M101JS/2014_June/about
C O U R S E   L E C T U R E 
MongoDB CRUD via Node.js
Notes taken on June 17, 2014 by Edward Tanguay
modifying documents
API for updating can update in various ways:
wholesale replacement
replacement of fields
upserts
updates take two arguments
everything you learned about find is applicable to updates
wholesale replacement
db.people.update({name : "Smith"}, {name : Thompson", salary : 50000 }
warning: the other fields will be deleted, it disregards what the datastore has and saves only what the application has
individual field replacement
need to add an age field
you need to know all the other fields
$set will add or modify a field
$inc will increment field
if doesn't have this field, then it will create it with the increment step
removing fields
$unset
manipulating arrays in documents
to change value, "a.2" = third element
$push adds to end of array
$pop to add to end or beginning
also $pushAll will add an array
$pull will remove the value from array no matter where it is
$pullAll pulls all values in an array from document array
$addToSet if value exists, it does nothing, if not, then it does a push
upserts
update document or, if does not exist, create a document
commonly used, e.g. merging data in from a data vendor
more than one update at a time
empty document matches all, but you need the option multi : true, otherwise it will only update one, and it is difficult to predict which one it will update
yielding means that concurrent write operations pause for other writes to take place, but no write operating will see a document half-updated
update all sores less tha 70 by 20
`db.scores.update( { 'score' : { $lt : 70 }}, {$inc : {score : 20}}, {multi:true})
deleting
delete one or many
if you specify an empty document, it will remove all (!)
db.people.remove( { } )
each individual remove operation is atomic, no remove operation will see another operation have finished
drop collection
db.people.drop()
to find out if command succeeded
db.runCommmand( { getLastError : 1 })
will show you if information about commands succeeded and failed
node.js driver and CRUD operations
we have been using the Mongo shell
first we need to import data
mongoimport -d course -c grades grades.json
example using findOne with the node.js driver
then node app.js to run it
notice the _id looks different as a JSON object as when we see it in the shell
to get multiple documents, use toArray
you can also get an array with a cursor, you get the cursor which does not have the array in it, you just call .each on an object that describes your query
you could also call .toArray on the object
the response from MongoDB is not the entire result set, only a certain batch size
find using field projection
you send in the project as a second argument
this way we are only sending data over the wire that we care about
with greater than and less then
dollar sign signifies a query operator
importing from Reddit
we will analyze data without necessarily knowing the structure of the data
in reddit, if you add /.json at the end you get a json document (actually didn't work)
tbe require('request') is to get data from other sites
regex queries via node
search for any document that has a title which contains "NSA"
db.reddit.find({ 'title' : { '$regex' : 'NSA'} });
then project out part of it
db.reddit.find({ 'title' : { '$regex' : 'NSA'} }, { 'title : 1, '_id' : 0 });
full code to print out these titles
dot notation in MongoDB queries
how to find embedded nodes in a JSON document
note that you can make queries even though you don't know if all the fields exist in the documents
sort, skip, limit (in that order)
the order will alway be in that order no matter how you add them in the code
sort with two fields
the order that they are in the array is the order they will sort
this is why you have an array instead of an object, since properties on an object do not have a guaranteed order
you can also use an option object:
inserting
insert is straightforward:
you can also store an a name in the _id field, which causes he driver not to generate it, but if you try to add it twice, you will get an error
you can also add numerous documents:
in MongoDB keys are case-sensitive so here two records will be inserted:
update
to update you need to get the document you want, change it, and then update it
notice we are doing two queries: between the two queries the document might have changed, you have to use the _id in the second query to make sure it is the same one
update with $set
multiple updates
upserts
how to upsert:
upserts can also be used with $set
notice $set sets two fields
save
find original document
the save function
findAndModify
atomically updates so that there isn't a wait period between finding and modifying
example to increment counter
we need sort to give us more control over which document we are updating, since there may be multiple documents, but if not, then leave sort empty
options specifies to pass the new, not the original, document back
remove
straightforward:
building a blog with node.js
starts node.js as web server
npm install
shows blog project
logs in / logs out
creates entry
creates comment
building a blog on node.js
app.js
requires
routes = require('./routes')
local file
UsersDAO and SessinosDAO are used to access MongoDB