java - How to find docs with arrays in which elements match some other element in another array? -


not sure if possible, here goes.

i have mongodb (using morphia access it) table following (simplified example, concept same):

{name:"product a", parts:[{sku:"w-01"},{sku:"y-01", qty:2}]} {name:"product b", parts:[{sku:"x-02"},{sku:"w-02"}]} {name:"product c", parts:[{sku:"z-01"}]} 

now want find products parts of sku starts "y" or "z". above docs, first , third should returned.

one possible query can imagine this:

{$or:[{"parts":{"$elemmatch":{sku:/y.*/}}},{"parts":{"$elemmatch":{sku:/z.*/}}}]} 

this needs loop through query arrays ["y","z"]

is there other way this? :)

instead of doing regular expression match, could split out first letter own subkey well:

{     name:"product a",      parts: [         { s: "w", ku: "w-01" },         { s: "y", ku: "y-01", qty:2 }     ] } 

otherwise can regular expression match — don't need $elemmatch here either.

db.products.find( { "parts.sku: /^[yz]/ } ); 

but better use $or each of them, @ least little bit of index can used regular expression search fixed-prefixed regular expression internally gets rewritten range query (y <= x < z) or (z <= x < [):

db.so.ensureindex( { 'parts.sku': 1 } ); db.products.find( { $or: [     { "parts.sku": /^y/ },     { "parts.sku": /^z/ }  ] } ); 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -