Databases Reference
In-Depth Information
Figure 1-3. If you store a document with the amount of room it will need in the future, it will not need
to be moved later.
Suppose we are programming a game where the player picks up various items. We
might model the player document as:
{
"_id" : "fred",
"items" : {
"slingshot" : {
"type" : "weapon",
"damage" : 23,
"ranged" : true
},
"jar" : {
"type" : "container",
"contains" : "fairy"
},
"sword" : {
"type" : "weapon",
"damage" : 50,
"ranged" : false
}
}
}
Now, suppose we want to find all weapons where
damage
is greater than 20. We can't!
Subdocuments do not allow you to reach into
items
and say, “Give me any item with
damage
greater than 20.” You can only ask for
specific
items: “Is
items.slingshot.dam
age
greater than 20? How about
items.sword.damage
?” and so on.
If you want to be able to access any item without knowing its identifier, you should
arrange your schema to store items in an array:
{
"_id" : "fred",