英文:
How to write query $centerSphere using mgo
问题
我已经阅读了[这里][1]的文档,其中讲述了如何编写查询以获取半径内的某些位置:
db.restaurants.find({ location:
{ $geoWithin:
{ $centerSphere: [ [ -73.93414657, 40.82302903 ], 5 / 3963.2 ] } } })
现在我尝试使用mgo
驱动程序编写它,但我不知道如何在这里编写它,以下是我尝试的代码:
var cites []City
collection := mongo.DB("Db").C("Collection")
err = collection.Find(bson.M{
"location": bson.M{
"$geoWithin": bson.M{
"$centerSphere": [ [ -73.93414657, 40.82302903 ], 5 / 3963.2 ],
},
},
}).All(&cites)
是的,上面的代码绝对不起作用,因为我不知道如何在Go中翻译`[ [ -73.93414657, 40.82302903 ], 5 / 3963.2 ]`。
[1]: https://docs.mongodb.com/manual/tutorial/geospatial-tutorial/#unsorted-with-geowithin
<details>
<summary>英文:</summary>
I have read the documentation [here][1] talks about writing query to get some location within the radius:
db.restaurants.find({ location:
{ $geoWithin:
{ $centerSphere: [ [ -73.93414657, 40.82302903 ], 5 / 3963.2 ] } } })
Now I try to write it using `mgo` driver but I don't get the idea how to write it here what I have tried :
var cites []City
collection := mongo.DB("Db").C("Collection")
err = collection.Find(bson.M{
"location": bson.M{
"$geoWithin": bson.M{
"$centerSphere" : [ [ -73.93414657, 40.82302903 ], 5 / 3963.2 ],
},
},
}).All(&cites)
Yes above code absolutely not working becuase I don't know how to translate this `[ [ -73.93414657, 40.82302903 ], 5 / 3963.2 ]` in go?
[1]: https://docs.mongodb.com/manual/tutorial/geospatial-tutorial/#unsorted-with-geowithin
</details>
# 答案1
**得分**: 3
对于[`$centerSphere`][1],您需要在类型为`[]interface{}`的切片中传递一个中心点和半径,其中点也是一个包含其坐标的切片,也可以是`[]interface{}`类型。
err = collection.Find(bson.M{
"location": bson.M{
"$geoWithin": bson.M{
"$centerSphere": []interface{}{
[]interface{}{-73.93414657, 40.82302903}, 5 / 3963.2,
},
},
},
}).All(&cites)
请参阅相关/可能的重复问题:
https://stackoverflow.com/questions/42619702/literal-usage-in-golang-mgo/42624044#42624044
[1]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere
<details>
<summary>英文:</summary>
For [`$centerSphere`][1] you have to pass a center point and a radius in a slice of type `[]interface{}`, where the point is also a slice containing its coordinates, can also be of type `[]interface{}`.
err = collection.Find(bson.M{
"location": bson.M{
"$geoWithin": bson.M{
"$centerSphere": []interface{}{
[]interface{}{-73.93414657, 40.82302903}, 5 / 3963.2,
},
},
},
}).All(&cites)
See a related / possible duplicate question:
https://stackoverflow.com/questions/42619702/literal-usage-in-golang-mgo/42624044#42624044
[1]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论