$literal usage in Golang-mgo

一笑奈何 提交于 2019-12-06 14:38:33

To be complete, this is what you actually try to do:

pipe := DB.C("store").Pipe([]bson.M{
    {"$project": bson.M{"location": bson.M{"type": bson.M{"$literal": "Point"}, "coordinates": []interface{}{"$longitude", "$latitude"}}}},
    {"$match": bson.M{"location": bson.M{"$geoWithin": bson.M{"$centerSphere": []interface{}{"$coordinates", 10 / 6378.11}}}}},
})

The problem is not with your "Point" literal, it's just a mere coincidence. If you change it to "Pt" for example, you will still see the exact same error message.

The Point in the error message refers to $centerSphere, which expects a center point and a radius. And the way you try to "pass" it does not work.

This works for example:

"$centerSphere": []interface{}{[]interface{}{1.0, 2.0}, 10 / 6378.11}

Your original query does not make sense, as you try to find documents where the location is within 10 kilometers from itself, which would match all documents.

Instead you want to / should query documents which are within 10 kilometers of a specific location, and you may pass the coordinates of this specific location to $centerSphere:

myLong, myLat := 10.0, 20.0

// ...

"$centerSphere": []interface{}{[]interface{}{myLong, myLat}, 10 / 6378.11}

The complete query:

myLong, myLat := 10.0, 20.0
pipe := DB.C("store").Pipe([]bson.M{
    {"$project": bson.M{"location": bson.M{"type": bson.M{"$literal": "Point"}, "coordinates": []interface{}{"$longitude", "$latitude"}}}},
    {"$match": bson.M{"location.coordinates": bson.M{"$geoWithin": bson.M{"$centerSphere": []interface{}{[]interface{}{myLong, myLat}, 10 / 6378.11}}}}},
})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!