Instead of doing a regular expression match, you could split out the first letter its own subkey as well:
{
name:"Product A",
parts: [
{ s: "W", ku: "W-01" },
{ s: "Y", ku: "Y-01", qty:2 }
]
}
Otherwise you can simply do this regular expression match — you don't need the $elemMatch
here either.
db.products.find( { "parts.sku: /^[YZ]/ } );
But it is better to use an $or
for each of them, as then at least a little bit of the index can be used as the regular expression search is now a fixed-prefixed regular expression that internally gets rewritten to a range query (Y <= x < Z
) or (Z <= x < [
):
db.so.ensureIndex( { 'parts.sku': 1 } );
db.products.find( { $or: [
{ "parts.sku": /^Y/ },
{ "parts.sku": /^Z/ }
] } );