Databases Reference
In-Depth Information
"items" : [
{
"id" : "slingshot",
"type" : "weapon",
"damage" : 23,
"ranged" : true
},
{
"id" : "jar",
"type" : "container",
"contains" : "fairy"
},
{
"id" : "sword",
"type" : "weapon",
"damage" : 50,
"ranged" : false
}
]
}
Now you can use a simple query such as
{"items.damage" : {"$gt" : 20}}
. If you need
more than one criteria of a given item matched (say,
damage
and
ranged
), you can use
$elemMatch
.
So, when should you use a subdocument instead of an array? When you know and will
always know the name of the field that you are accessing.
For example, suppose we keep track of a player's abilities: her strength, intelligence,
wisdom, dexterity, constitution, and charisma. We will always know which specific
ability we are looking for, so we could store this as:
{
"_id" : "fred",
"race" : "gnome",
"class" : "illusionist",
"abilities" : {
"str" : 20,
"int" : 12,
"wis" : 18,
"dex" : 24,
"con" : 23,
"cha" : 22
}
}
When we want to find a specific skill, we can look up
abilities.str
, or
abili
ties.con
, or whatever. We'll never want to find some ability that's greater than 20,
we'll always know what we're looking for.