Database Reference
In-Depth Information
db.products.ensureIndex({"attrs.freq_low": 1, "attrs.freq_hi": 1},
{sparse: true})
You can also efficiently search hard disks by rotation speed with the following index:
db.products.ensureIndex({"attrs.rotation": 1}, {sparse: true})
The overall strategy here is to scope your attributes for readability and app discover-
ability and to use sparse indexes to keep null values out of the indexes.
If your attributes are completely unpredictable, then you can't build a separate
index for each one. You have to use a different strategy in this case as illustrated by the
following sample document:
{ _id: ObjectId("4d669c225d3a52568ce07646")
sku: "ebd-123"
name: "Hi-Fi Earbuds",
type: "Headphone",
attrs: [ {n: "color", v: "silver"},
{n: "freq_low", v: 20},
{n: "freq_hi", v: 22000},
{n: "weight", v: 0.5}
]
}
Here attrs points to an array of sub-documents. Each of these documents has two val-
ues, n and v , corresponding to each dynamic attribute's name and value. This normal-
ized representation allows you to index these attributes using a single compound index:
db.products.ensureIndex({"attrs.n": 1, "attrs.v": 1})
You can then query using these attributes, but to do that, you must use the $elem-
Match query operator:
db.products.find({attrs: {$elemMatch: {n: "color", v: "silver"}}})
Note that this strategy incurs a lot of overhead since it requires storing the key names
in the index. It would be important to test this for performance on a representative
data set before going into production.
B.1.7
Transactions
MongoDB doesn't provide ACID guarantees over a series of operations, and no equiv-
alent of RDBMS s' BEGIN , COMMIT , and ROLLBACK semantics exists. When you need these
features, use a different database (either for the data that needs proper transactions
or for the application as a whole). Still MongoDB supports atomic, durable updates
on individual documents and consistent reads, and these features, though primitive,
can be used to implement transaction-like behavior in an application.
You saw an extended example of this in chapter 6's treatments of order authoriza-
tion and inventory management. And the worker queue implementation earlier in
this appendix could easily be modified to support rollback. In both cases, the founda-
tion for transaction-like behavior is the ever-versatile findAndModify command, which
is used to atomically manipulate a state field on one or more documents.
Search WWH ::




Custom Search