【问题标题】:Get distance between two geo-locations from MongoDB从 MongoDB 获取两个地理位置之间的距离
【发布时间】:2020-10-06 00:30:03
【问题描述】:

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

我关注了this answer 并尝试了这个

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)

但我收到此错误:"Invalid Argument in geo near query:near"

【问题讨论】:

    标签: mongodb go


    【解决方案1】:

    Mentioned Answer 使用 MongoDB aggregate 函数。

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

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

    还可以查看此快速指南,了解如何在 golang 和 mongo 中使用聚合管道 Golang & MongoDB - Data Aggregation Pipeline

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-24
      • 2011-02-14
      • 2013-08-21
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多