簡體   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