mongodb文件'内容'是
{
"_id" : ObjectId("57bd1ff410ea3c38386b9194"),
"name" : "4Fingers",
"locations" : [
{
"id" : "locations1",
"address" : "68 Orchard Rd, #B1-07 Plaza Singapura, Plaza Singapura, Singapura 238839",
"phone" : "+65 6338 0631",
"openhours" : "Sunday-Thursday: 11am - 10pm \nFriday/Saturday/Eve of PH*: 11am - 11pm",
"loc" : [
"1.300626",
"103.845061"
]
}
],
"comments" : [ ],
"modified" : 1472271793525,
"created" : 1472012276724,
"createdby" : "Admin",
"modifiedby" : "Admin",
"createdipaddress" : "localhost",
"modifiedipaddress" : null,
"types" : "Restaurant",
"category" : "FoodAndBeverages",
"logo" : "logo4Fingers.png",
"tags" : "western, chicken, restaurant, food, beverages"
}
我想从HTML5导航中找到离我所在位置最近的地方。我该如何查询?数据应按近似顺序排序。
谢谢。
答案 0 :(得分:0)
要首先查询mongodb地理空间数据,您需要在您的位置字段上使用地理空间索引。
您的位置字段是字符串,需要是数字类型,您需要相应地更新数据。
在数字位置数据上创建索引:
db.collection.createIndex( { "locations.loc" : "2d" });
查询:
var projection = {"locations.loc":1};
var query = {"locations.loc": {"$near":[1.300626, 103.845061], "$maxDistance": 0.5}};
db.collection.find(query, projection).pretty();
//result:
{
"_id" : ObjectId("57bd1ff410ea3c38386b9194"),
"locations" : [
{
"loc" : [
1.300626,
103.845061
]
}
]
}
var query2 = {"locations.loc": {"$near":[2.300626, 103.845061], "$maxDistance": 0.5}};
db.collection.find(query2, projection).pretty();
//result:
{}
查询结果将始终排序,最接近第一个文档。
答案 1 :(得分:0)
感谢Sergiu Zaharie。
它正在运作。
然后我怎样才能返回所有字段而不是仅返回此字段。
{
"_id" : ObjectId("57bd1ff410ea3c38386b9194"),
"locations" : [
{
"loc" : [
103.845061,
1.300626
]
}
]
}
//修改
解决。
我只是清除了投影,然后就像魅力一样。
谢谢。