Database Reference
In-Depth Information
2.1.2
Inserts and queries
If no other database is specified on startup, the shell selects a default database called
test
. As a way of keeping all the subsequent tutorial exercises under the same
namespace, let's start by switching to the
tutorial
database:
> use tutorial
switched to db tutorial
You'll see a message verifying that you've switched databases.
ON CREATING DATABASES AND COLLECTIONS
You may be wondering how we
can switch to the tutorial database without explicitly creating it. In fact, creat-
ing the database isn't required. Databases and collections are created only
when documents are first inserted. This behavior is consistent with
MongoDB's dynamic approach to data; just as the structure of documents
need not be defined in advance, individual collections and databases can be
created at runtime. This can lead to a simplified and accelerated develop-
ment process, and essentially facilitates dynamic namespace allocation, which
can frequently be useful. That said, if you're concerned about databases or
collections being created accidentally, most of the drivers let you enable a
strict mode
to prevent such careless errors.
It's time to create your first document. Since you're using a JavaScript shell, your doc-
uments will be specified in
JSON
(JavaScript Object Notation). For instance, the sim-
plest imaginable document describing a user might look like this:
{username: "jones"}
The document contains a single key and value for storing Jones's username. To save
this document, you need to choose a collection to save it to. Appropriately enough,
you'll save it to the
users
collection. Here's how:
> db.users.insert({username: "smith"})
You may notice a slight delay after entering this code. At this point, neither the
tutorial
database nor the
users
collection has been created on disk. The delay is
caused by the allocation of the initial data files for both.
If the insert succeeds, then you've just saved your first document. You can issue a
simple query to verify that the document has been saved:
> db.users.find()
The response will look something like this:
{ _id : ObjectId("4bf9bec50e32f82523389314"), username : "smith" }
Note that an
_id
field has been added to the document. You can think of the
_id
value as the document's primary key. Every MongoDB document requires an
_id
,
and if one isn't present when the document is created, then a special MongoDB
object
ID
will be generated and added to the document at that time. The object
ID
that appears in your console won't be the same as the one in the code listing, but it