ruby on rails - MongoDB/Mongoid: search for documents matching first item in array -
i have document has array:
{ _id: objectid("515e10784903724d72000003"), association_chain: [ { name: "product", id: objectid("4e1e2cdd9a86652647000003") } ], //... } i'm trying search collection documents name of first item in association_chain array matches given value.
how can using mongoid? or if know how can done using mongodb, if post example, figure out how mongoid.
two ways this:
1) if know you're interested in first product name appearing in "association_chain", better:
db.items.find("association_chain.0.name":"something") please note not return items, mention desired product, mention in first position of 'association_chain' array.
if want this, you'll need index:
db.items.ensureindex({"association_chain.0.name":1},{background:1}) 2) if looking specific product, not sure in position of association_chain appears, this:
with mongodb shell can access hash key inside nested structure '.' dot operator! please note independent of how key nested in record (isn't cool?)
you can find on embedded array of hashes this:
db.items.find("association_chain.name":"something") this returns records in collection contain desired product mentioned anywhere in association_array.
if want this, should make sure have index:
db.items.ensureindex({"association_chain.name":1},{background: 1}) see "dot notation" on page: http://docs.mongodb.org/manual/core/document/
Comments
Post a Comment