How to do query on multiple nested data fields in MongoDB -
so, i'm trying query documents have city of 'paris' and state of 'france'. need kind of join, haven't been able figure out how construct it.
i'm using c# driver, i'll gladly accept using method.
{ "_id" : objectid("519b407f3c22a73a7c29269f"), "documentid" : "1", "meta" : [{ "name" : "city", "value" : "paris", }, { "name" : "state", "value" : "france", } }] } { "_id" : objectid("519b407f3c22a73a7c29269g"), "documentid" : "2", "meta" : [{ "name" : "city", "value" : "paris", }, { "name" : "state", "value" : "texas", } }] }
the $elemmatch
operator used indicate conditions within must matched same array element. (to switch shell syntax) match documents have meta city paris do
db.collection.find( {meta:{$elemmatch:{name:"city",value:"paris"}}} )
this assures won't match has name: "somethingelse", value: "paris" somewhere in array different array element matching name:"city".
now, default combination combining query conditions "and" can continue adding attributes:
db.collection.find( {meta: { $elemmatch:{name:"city",value:"paris"}, $elemmatch:{name:"state",value:"france"} } } )
now if want add condition keep adding if want not this:
db.collection.find( {meta: { $elemmatch:{name:"city",value:"paris"}, $elemmatch:{name:"state",value:"france"}, $not: {$elemmatch:{name:"arrondissement",value:"louvre"}} } } )
Comments
Post a Comment