Database Reference
In-Depth Information
> db.numbers.find({n: {$type: 1}});
{ "_id" : ObjectId("4c581c98d5bbeb2365a838f9"), "n" : 5 }
> db.numbers.find({n: {$type: 18}});
{ "_id" : ObjectId("4c581c9bd5bbeb2365a838fa"), "n" : NumberLong( 5 ) }
This verifies the difference in storage. You'll probably never use the $type operator in
production, but as seen here, it's a great tool for debugging.
The only other issue that commonly arises with BSON numeric types is the lack of
decimal support. This means that if you're planning on storing currency values in
MongoDB, you need to use an integer type and keep the values in cents.
Datetimes
The BSON datetime type is used to store temporal values. Time values are represented
using a signed 64-bit integer marking milliseconds since the Unix epoch, in UTC
(Coordinated Universal Time). A negative value marks milliseconds prior to the
epoch. 11
A couple usage notes follow. First, if you're creating dates in JavaScript, keep in mind
that months in JavaScript dates are 0-based. This means that new Date(2011, 5, 11) will
create a date object representing June 11, 2011. Next, if you're using the Ruby driver to
store temporal data, the BSON serializer expects a Ruby Time object in UTC. Conse-
quently, you can't use date classes that maintain a time zone since a BSON datetime can't
encode that data.
Custom types
But what if you must store your times with their time zones? Sometimes the basic
BSON types don't suffice. Though there's no way to create a custom BSON type, you
can compose the various primitive BSON values to create your own virtual type. For
instance, if you wanted to store times with zone, you might use a document structure
like this, in Ruby:
{:time_with_zone =>
{:time => Time.utc.now,
:zone => "EST"
}
}
It's not difficult to write an application so that it transparently handles these compos-
ite representations. This is usually how it's done in the real world. For example,
MongoMapper, an object mapper for MongoDB written in Ruby, allows you to define
to_mongo and from_mongo methods for any object to accommodate these sorts of cus-
tom composite types.
11
The Unix epoch is defined as midnight, January 1, 1970, coordinated universal time.
Search WWH ::




Custom Search