Nested $and or grouped $and in MongoDB -
consider following document:
{ "_id" : objectid("5130f9a677e23b11503fee55"), "itemtype" : "bicycle" "attributes" : [{ "attributename" : "spare tire", "attributevalue" : "1" }, { "attributename" : "with helmet?", "attributevalue" : "0" }, { "attributename" : "number of locks", "attributevalue" : "1" }] }
how write query bicycles spare tire , no helmet?
i tried following doesn't give me want.
{ "$and" : [ { "itemtype" : "bicycle" }, { "$and": [{ "attributes.attributename" : "with helmet?" }, { "attributes.attributevalue" : "0" } ]}, { "$and": [{ "attributes.attributename" : "spare tire" }, { "attributes.attributevalue" : "1" } ]} ]}
it seems long there value matches attributes.attributevalue
- regardless of accompanying attributes.attributename
- returns document. it's having query:
{ "$and" : [ { "itemtype" : "bicycle" }, //true { "attributes.attributename" : "with helmet?" }, //true { "attributes.attributename" : "spare tire" }, //true { "attributes.attributevalue" : "0" }, //any { "attributes.attributevalue" : "1" } //any ]}
i believe looking $elemmatch
here, whereby makes sure correspoding attributename
, attributevalue
in same element of multi-value field ( http://docs.mongodb.org/manual/reference/operator/elemmatch/ ):
{ itemtype: 'bicycle', $and:[ {"attributes": {$elemmatch:{attributename: 'with helmet?', attributevalue: 0 }}}, { //next match } ] }
try that
Comments
Post a Comment