mongoose - Mongodb -Moogose query array fields filter -
i want filter when agg : 6 , 'value' greater : 1000 , agg : 5 , 'value' greater : 2000 schema: posting
query:db.postings.find( { agg: { $elemmatch: { $and:[ {agg:'5', value: { $gte: '2000'} }, {agg:'6', value: { $gte: '1000'} } ] } }} ); result : [] empty
collection':
{ "_id":1, "agg" : [ { "value" : "2014", "agg" : "5"}, {"value" : "2500","agg" : "6"} ], } { _id:2, "agg" : [ { "value" : "2015", "agg" : "5"}, { "value" : "1000","agg" : "6" } ], } how write query correctly?
it looks want documents agg array satisfies following condition:
contains subdocument agg = "6" , value >= "2000" , contains subdocument agg = "5" , value >= "1000" your query documents agg subarray satisfies following condition:
contains subdocument agg = "6" , value >= "2000" , agg = "5" , value >= "1000" the mongodb formulation of correct query is
{ "$and" : [ { "agg" : { "$elemmatch" : { "agg" : "5", "value" : { "$gte" : "2000" } } } }, { "agg" : { "$elemmatch" : { "agg" : "6", "value" : { "$gte" : "1000" } } } } ] } equivalently $all,
{ "agg" : { "$all" : [ { "$elemmatch" : { "agg" : "5", "value" : { "$gte" : "2000" } } }, { "$elemmatch" : { "agg" : "6", "value" : { "$gte" : "1000" } } } ] } } this query matches both documents, guess expected. however, still have doubts you're doing intend - sure want values of agg.agg , agg.value strings , not numbers? example, following document matches query:
{ "_id" : 3, "agg" : [ { "agg" : "5", "value" : "2015" }, { "agg" : "6", "value" : "potato" } ] } this document not:
{ "_id" : 4, "agg" : [ { "agg" : "5", "value" : "2015" }, { "agg" : "6", "value" : 2000 } ] }
Comments
Post a Comment