django - Mongoengine query to return matching elements from an array of the same document in a collection -
what mongoengine query return locations names starts "b" below document of collection?
{ "_id" : objectid("5388ae8df30090186310ed77"), "city" : "pune", "locations" : [ "kalyani nagar", "vishrantwadi", "camp", "bhawani peth", "kasarwadi", "deccan gymkhana", "dhankawadi", "wanowrie", "sinhagad road-vadgaon budruk", "kothrud", "pune cantonment", "bibvewadi", "shivaji nagar", "pimple nilakh-pimpri chinchwad", "thergaon", "dapodi", "wakad", "katraj", "pashan gaon" ] }
collection.objects(locations__istartswith = "b",city__iexact = "pune").distinct("locations")
is not giving expected result.
what need aggregation framework methods mongodb in order there "multiple" matches condition , cannot solved simple query projection. essential statement goes this, considering multiple documents match condition:
db.collection.aggregate([ // match documents satisfy condition { "$match": { "city": "pune", "locations": { "$regex": "^b" } }}, // unwind array individual documents { "$unwind": "$locations" }, // match "filter" array elements { "$match": { "locations": { "$regex": "^b" } }}, // group documents if required { "$group": { "_id": "$_id", "city": { "$first": "$city" }, "locations": { "$push": "$locations" } }}
so $regex
match values of "locations" starting "b" filtering work required. first matching documents in collection meet condition, after $uwnind
of array in matching documents it used again "filter" actual array entries.
optionally put document matching array elements in response using $group
. document result be:
{ "_id" : objectid("5388ae8df30090186310ed77"), "city" : "pune", "locations" : [ "bhawani peth", "bibvewadi", ] }
note $regex
can modified whatever need or case insensitive, efficient form "start with" in exact case shown. use possible.
this require access raw "pymongo" driver underlying mongoengine in order basic "collection" object , use aggregate method. i'm not sure on correct method sources vary, link may of doing part.
Comments
Post a Comment