Chapter Introduction

This chapter introduces Golang MongoDB geospatial queries, including how to store location information and query by distance.

Prerequisite Tutorials

Tip: If you are not familiar with MongoDB query syntax, please read the MongoDB tutorial first. The expression syntax used for operating MongoDB in Golang is the same.

Prepare Test Data

Write some data containing geographical coordinates into the coll collection. The location field stores the latitude and longitude coordinates of the stores.

docs := []interface{}{
    bson.D{
        {"title", "Hainan Steamed Chicken"},
        {"location", bson.D{
            {"type": "Point"},
            {"coordinates": bson.A{116.240015, 39.899617}}
        }},
    },
    bson.D{
        {"title", "Guangdong BBQ Pork"},
        {"location", bson.D{
            {"type": "Point"},
            {"coordinates": bson.A{116.268854, 39.900276}}
        }},
    },
    bson.D{
        {"title", "Guangdong Roast Goose"},
        {"location", bson.D{
            {"type": "Point"},
            {"coordinates": bson.A{116.264905, 39.902778}}
        }},
    },
    bson.D{
        {"title", "Shanxi Pancake"},
        {"location", bson.D{
            {"type": "Point"},
            {"coordinates": bson.A{116.288938, 39.893164}}
        }},
    },
    bson.D{
        {"title", "Hangzhou Dumplings"},
        {"location", bson.D{
            {"type": "Point"},
            {"coordinates": bson.A{116.286191, 39.910415}}
        }},
    }
}

result, err := coll.InsertMany(context.Background(), docs)

Query by Distance

Use the $near operator to implement a distance query. Assuming the coll collection stores store data, and the location field stores the coordinates of each store, the following code queries the nearest store to me (minimum distance 1000 meters, maximum distance 5000 meters).

cursor, err := coll.Find(
    context.Background(),
    bson.D{{"location", bson.D{
        {"$near": bson.D{
            {"$geometry": bson.D{{"type":"Point"}, {"coordinates": bson.A{116.288938,39.893164}}}, // My current coordinates
            {"$minDistance": 1000}, // Minimum distance
            {"$maxDistance": 5000} // Maximum distance
        }}
    }}}
)

Equivalent expression:

{
     location:
       { $near :
          {
            $geometry: { type: "Point",  coordinates: [ -73.9667, 40.78 ] }, // My coordinates
            $minDistance: 1000, // Minimum distance
            $maxDistance: 5000 // Maximum distance
          }
       }
}

The expression is the same as the native MongoDB expression, the only difference is to re-describe it using Golang’s data structure.