Databases Reference
In-Depth Information
A MongoDB Client
Although the ability to execute arbitrary JavaScript is cool, the real power of the shell
lies in the fact that it is also a stand-alone MongoDB client. On startup, the shell con-
nects to the test database on a MongoDB server and assigns this database connection
to the global variable db . This variable is the primary access point to MongoDB through
the shell.
The shell contains some add-ons that are not valid JavaScript syntax but were imple-
mented because of their familiarity to users of SQL shells. The add-ons do not provide
any extra functionality, but they are nice syntactic sugar. For instance, one of the most
important operations is selecting which database to use:
> use foobar
switched to db foobar
Now if you look at the db variable, you can see that it refers to the foobar database:
> db
foobar
Because this is a JavaScript shell, typing a variable will convert the variable to a string
(in this case, the database name) and print it.
Collections can be accessed from the db variable. For example, db.baz returns the baz
collection in the current database. Now that we can access a collection in the shell, we
can perform almost any database operation.
Basic Operations with the Shell
We can use the four basic operations, create, read, update, and delete (CRUD), to
manipulate and view data in the shell.
Create
The insert function adds a document to a collection. For example, suppose we want
to store a blog post. First, we'll create a local variable called post that is a JavaScript
object representing our document. It will have the keys "title" , "content" , and
"date" (the date that it was published):
> post = {"title" : "My Blog Post",
... "content" : "Here's my blog post.",
... "date" : new Date()}
{
"title" : "My Blog Post",
"content" : "Here's my blog post.",
"date" : "Sat Dec 12 2009 11:23:21 GMT-0500 (EST)"
}
This object is a valid MongoDB document, so we can save it to the blog collection using
the insert method:
 
Search WWH ::




Custom Search