简体   繁体   English

从 MongoDB 获取两个地理位置之间的距离

[英]Get distance between two geo-locations from MongoDB

I'm trying to get the distance between two points on a 2dsphere from MongoDB using Go.我正在尝试使用 Go 从 MongoDB 获取 2dsphere 上两点之间的距离。

I followed this answer and tried this我按照这个答案尝试了这个

conditions["geolocation"] = bson.M{
        "$geoNear": bson.M{
            "near": bson.M{
                "type":        "Point",
                "coordinates": []float64{latitude, longitude},
            },
            "maxDistance":   rangeInMeters,
            "spherical":     true,
            "distanceField": "distance",
        },
    }

filterCursor, err := collection.Find(ctx, conditions)

But I get this error: "Invalid arguement in geo near query:near"但我收到此错误: “地理附近查询中的无效争论:near”

The Mentioned Answer uses MongoDB aggregate function. 提到的答案使用 MongoDB聚合function。

You can do that with golang like follows:您可以使用 golang 执行此操作,如下所示:

    stages := mongo.Pipeline{}
    getNearbyStage := bson.D{{"$geoNear", bson.M{
        "near": bson.M{
            "type":        "Point",
            "coordinates": []float64{latitude, longitude},
        },
        "maxDistance":   rangeInMeters,
        "spherical":     true,
        "distanceField": "distance",
    }}}
    stages = append(stages, getNearbyStage)

    filterCursor, err := collection.Aggregate(ctx, stages)

    if err != nil {
        log.Println(err)
        return nil, err
    }



If you want to add another query to the pipleline you can simply make another stage and append it to the stages slice如果您想向管道添加另一个查询,您可以简单地制作另一个阶段并将 append 它添加到阶段切片

also check this quick guide on how to use Aggregation Pipelines in golang & mongo Golang & MongoDB - Data Aggregation Pipeline另请查看有关如何在 golang 和 mongo Golang 和 MongoDB - 数据聚合管道中使用聚合管道的快速指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM