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

从MongoDB获取两个地理位置之间的距离,mongodb,go,Mongodb,Go,我正在尝试使用Go从MongoDB获得2D球体上两点之间的距离 我跟随并尝试了这个 conditions["geolocation"] = bson.M{ "$geoNear": bson.M{ "near": bson.M{ "type": "Point", "coordinates": []float64{latitude, longitude}, }

我正在尝试使用Go从MongoDB获得2D球体上两点之间的距离

我跟随并尝试了这个

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)
但是我得到了这个错误:“geo-near查询中的参数无效:near”

使用MongoDB函数

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



如果您想向pipleline添加另一个查询,只需创建另一个stage并将其附加到stages切片

另外,请查看本快速指南,了解如何在golang&mongo中使用聚合管道