Databases Reference
In-Depth Information
upsert ? true : false, multi ? true : false);
}
There is also an autogenerated API of all the JavaScript functions provided by the shell
Inconvenient collection names
Fetching a collection with
db.
collectionName
almost always works, unless the collec-
tion name actually is a property of the database class. For instance, if we are trying to
access the
version
collection, we cannot say
db.version
because
db.version
is a database
function. (It returns the version of the running MongoDB server.)
> db.version
function () {
return this.serverBuildInfo().version;
}
db
's collection-returning behavior is only a fallback for when JavaScript cannot find a
matching property. When there is a property with the same name as the desired col-
lection, we can use the
getCollection
function:
> db.getCollection("version");
test.version
This can also be handy for collections with invalid JavaScript in their names. For ex-
ample,
foo-bar
is a valid collection name, but it's variable subtraction in JavaScript.
You can get the
foo-bar
collection with
db.getCollection("foo-bar")
.
In JavaScript,
x.y
is identical to
x['y']
. This means that subcollections can be accessed
using variables, not just literal names. That is, if you needed to perform some operation
on every
blog
subcollection, you could iterate through them with something like this:
var collections = ["posts", "comments", "authors"];
for (i in collections) {
doStuff(db.blog[collections[i]]);
}
Instead of this:
doStuff(db.blog.posts);
doStuff(db.blog.comments);
doStuff(db.blog.authors);
Data Types
The beginning of this chapter covered the basics of what a document is. Now that you
are up and running with MongoDB and can try things on the shell, this section will
dive a little deeper. MongoDB supports a wide range of data types as values in docu-
ments. In this section, we'll outline all of the supported types.