登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-27 23:51:35 162浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《从 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”


解决方案


Mentioned Answer 使用 mongodb aggregate 函数。

你可以使用 golang 来做到这一点,如下所示:

stages := mongo.Pipeline{}
    getNearbyStage := bson.D{{"$geoNear", bson.M{
        "near": bson.M{
            "type":        "Point",
            "coordinates": []float64{longitude, latitude},
        },
        "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
    }

如果您想向管道添加另一个查询,您可以简单地创建另一个阶段并将其附加到阶段切片

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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>