繁体   English   中英

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

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

我正在尝试使用 Go 从 MongoDB 获取 2dsphere 上两点之间的距离。

我按照这个答案尝试了这个

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)

但我收到此错误: “地理附近查询中的无效争论:near”

提到的答案使用 MongoDB聚合function。

您可以使用 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
    }



如果您想向管道添加另一个查询,您可以简单地制作另一个阶段并将 append 它添加到阶段切片

另请查看有关如何在 golang 和 mongo Golang 和 MongoDB - 数据聚合管道中使用聚合管道的快速指南

暂无
暂无

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

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