|
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 |
API for updating can update in various ways:
updates take two arguments
everything you learned about find is applicable to updates
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
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
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})
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
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
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
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
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:
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:
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
upserts can also be used with $set
notice $set sets two fields
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
building a blog with node.js
starts node.js as web server
building a blog on node.js
routes = require('./routes')
UsersDAO and SessinosDAO are used to access MongoDB