Database Reference
In-Depth Information
compound key consisting of a stock symbol and a timestamp. Here's how a representa-
tive document might look: 7
{ _id: {sym: 'GOOG', date: 20101005}
open: 40.23,
high: 45.50,
low: 38.81,
close: 41.22
}
You could then find the summary of GOOG for October 5, 2010 with the following _id
query:
db.ticks.find({_id: {sym: 'GOOG', date: 20101005} });
It's important to realize that a query matching an entire object like this will perform a
strict byte-by-byte comparison, which means that the order of the keys matters. The
following query isn't equivalent and won't match the sample document:
db.ticks.find({_id: {date: 20101005, sym: 'GOOG'} });
Though the order of keys will be preserved in JSON documents entered via the shell,
this isn't necessarily true for document representations in all the various language
drivers. For example, hashes in Ruby 1.8 aren't order-preserving. To preserve key
order in Ruby 1.8, you must use an object of class BSON::OrderedHash instead:
doc = BSON::OrderedHash.new
doc['sym'] = 'GOOG'
doc['date'] = 20101005
@ticks.find(doc)
Be sure to check whether the language you're using supports ordered dictionaries; if
not, the language's MongoDB driver will always provide an ordered alternative.
A RRAYS
Arrays give the document model much of its power. As you've seen, arrays are used to
store lists of strings, object ID s, and even other documents. Arrays afford rich yet com-
prehensible documents; it stands to reason that MongoDB would let query and index
the array type with ease. And it's true: the simplest array queries look just like queries
on any other document type. Take product tags again. These tags are represented as a
simple list of strings:
{ _id: ObjectId("4c4b1476238d3b4dd5003981"),
slug: "wheel-barrow-9092",
sku: "9092",
tags: ["tools", "equipment", "soil"] }
Querying for products with the tag soil is trivial and uses the same syntax as querying a
single document value:
db.products.find({tags: "soil"})
7
In a potential high-throughput scenario, you'd want to limit document size as much as possible. You could
accomplish this in part by using short key names. Thus you might use the key name o in place of open .
Search WWH ::




Custom Search