Databases Reference
In-Depth Information
JavaScript program (instead of a series of shell commands—scripts can be run with
mongo scriptname.js ), it might look something like the following:
// check if we have an entry for this page
blog = db.analytics.findOne({url : "/blog"})
// if we do, add one to the number of views and save
if (blog) {
blog.pageviews++;
db.analytics.save(blog);
}
// otherwise, create a new document for this page
else {
db.analytics.save({url : "/blog", pageviews : 1})
}
This means we are making a round-trip to the database, plus sending an update or
insert, every time someone visits a page. If we are running this code in multiple pro-
cesses, we are also subject to a race condition where more than one document can be
inserted for a given URL.
We can eliminate the race condition and cut down on the amount of code by just
sending an upsert (the third parameter to update specifies that this should be an upsert):
db.analytics.update({"url" : "/blog"}, {"$inc" : {"visits" : 1}}, true)
This line does exactly what the previous code block does, except it's faster and atomic!
The new document is created using the criteria document as a base and applying any
modifier documents to it. For example, if you do an upsert that matches a key and has
an increment to the value of that key, the increment will be applied to the match:
> db.math.remove()
> db.math.update({"count" : 25}, {"$inc" : {"count" : 3}}, true)
> db.math.findOne()
{
"_id" : ObjectId("4b3295f26cc613d5ee93018f"),
"count" : 28
}
The remove empties the collection, so there are no documents. The upsert creates a new
document with a "count" of 25 and then increments that by 3, giving us a document
where "count" is 28. If the upsert option were not specified, {"count" : 25} would not
match any documents, so nothing would happen.
If we run the upsert again (with the criteria {count : 25} ), it will create another new
document. This is because the criteria does not match the only document in the col-
lection. (Its "count" is 28.)
The save Shell Helper
save is a shell function that lets you insert a document if it doesn't exist and update it
if it does. It takes one argument: a document. If the document contains an "_id" key,
 
Search WWH ::




Custom Search