MongoDB
 SQL >> Datenbank >  >> NoSQL >> MongoDB

Das passende Subdokument mit $geoNear zurückgeben

Die gesuchte Option bei $geoNear heißt includeLocs:

Store.aggregate([ { "$geoNear": { "near": [ -70.64341379999999, -33.4268697 ], "distanceField": "distance", "maxDistance": 0.0900899926955034, "includeLocs": "location" }} ])

Die Ausgabe enthält die gefundene Position zusammen mit der berechneten Distanz:

{ "_id" : ObjectId("5507b18d1c3bdce0535aecd0"), "name" : "store1", "branchoffices" : [ { "name" : "bo1", "location" : [ -70.64341379999999, -33.4268697 ] }, { "name" : "bo2", "location" : [ 80.4, 43.3 ] } ], "distance" : 0, "location" : [ -70.64341379999999, -33.4268697 ] }

Das komplette passende Subdokument

Wenn Sie das vollständige Filialobjekt statt nur der Koordinaten brauchen, ergänzen Sie einen Filter mit $redact:

Store.aggregate([ { "$geoNear": { "near": [ -70.64341379999999, -33.4268697 ], "distanceField": "distance", "maxDistance": 0.0900899926955034, "includeLocs": "location" }}, { "$redact": { "$cond": [ { "$eq": [ "$location", "$$ROOT.location" ] }, "$$DESCEND", "$$PRUNE" ]}} ])

Bei MongoDB-Versionen vor 2.6 entspricht das einer Abfolge aus $unwind, $match und $group:

Store.aggregate([ { "$geoNear": { "near": [ -70.64341379999999, -33.4268697 ], "distanceField": "distance", "maxDistance": 0.0900899926955034, "includeLocs": "location" }}, { "$unwind": "$branchoffices" }, { "$project": { "name": 1, "branchoffices": 1, "matched": { "$eq": [ "$location", "$branchoffices.location" ] } }}, { "$match": { "matched": 1 } }, { "$group": { "_id": "$_id", "name": { "$first": "$name" }, "branchoffices": { "$push": "$branchoffices" }, "distance": { "$first": "$distance" } }} ])

Ein Hinweis zum Design

Positionen innerhalb eines Subdokument-Arrays zu verschachteln ist oft die falsche Struktur. Wenn ein Array-Element mehrere Punkte in der Nähe der Abfrage enthalten kann, ist auf diesem Weg nur der jeweils nächste matchbar. In den meisten Fällen gehören Geodaten in ein eigenes Dokument – das macht auch Geoindexierung und Abfragen deutlich flexibler.