#进入容器
docker exec -it mongodb /bin/bash
use testdb
db.house.createIndex({loc:'2d'}) #为house表的loc字段创建地理2d索引
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
db.house.createIndex({hid:1},{unique:true}) #为house表的hid字段创建唯一索引
#通过百度api查询地址的经纬度
http://api.map.baidu.com/geocoder/v2/?address=上海
xxxx&ak=jpfEH2etB2gutGyHpxVdWy8ZrTxbu0qj&output=json
#插入测试数据
db.house.insert({hid:1,title:'整租 · 南丹大楼 1居室 7500',loc:[121.4482236974557,31.196523937504549]})
db.house.insert({hid:2,title:'陆家嘴板块,精装设计一室一厅,可拎包入住诚意租。',loc:[121.51804613891443,31.238878702131506]})
db.house.insert({hid:3,title:'整租 · 健安坊 1居室 4050',loc:[121.4148310693774,31.16507733043528]})
db.house.insert({hid:4,title:'整租 · 中凯城市之光+视野开阔+景色秀丽+拎包入住',loc:[121.43528282056717,31.198687949417815]})
db.house.insert({hid:5,title:'整租 · 南京西路品质小区 21213三轨交汇 配套齐* 拎包入住',loc:[121.43528282056717,31.198687949417815]})
db.house.insert({hid:6,title:'祥康里 简约风格 *南户型 拎包入住 看房随时',loc:[121.47521508401232,31.23859308719981]
db.house.insert({hid:7,title:'整租 · 桃源新村 1室0厅 5500元',loc:[121.488377804633,31.23113867155927]})
db.house.insert({hid:8,title:'整租 · 中山公园品质小区,两房朝南厅朝南,家电家具精装*配',loc:[121.42038642151562,31.225078800208654]})
db.house.insert({hid:9,title:'整租 · 近地铁2号线,精装1房1厅,高区朝南,享受阳光好房',loc:[121.42933310871683,31.221943586471036]})
db.house.insert({hid:10,title:'整租 · 2.3.4号中山公园地铁,背靠来福士,采光好,诚意出租',loc:[121.42063977421182,31.221023374982044]})
#查询上海人民广场附近5公里的房源,人民广场的坐标为:121.48130241985999,31.235156971414239
db.house.find({loc:{$near:[121.48130241985999,31.235156971414239],$maxDistance:5/111.12 }})
#注意距离要除以111.2(1度=111.2km),跟普通查找的区别仅仅是多了两个算子$near和$maxDistance
#查询结果:
{ "_id" : ObjectId("5c1c99cd4729d1aaa1bdbbf3"), "hid" : 6, "title" : "祥康里 简约风格 *南户型 拎包入住 看房随时", "loc" : [ 121.47521508401232, 31.23859308719981 ] }
{ "_id" : ObjectId("5c1c99cd4729d1aaa1bdbbf4"), "hid" : 7, "title" : "整租 · 桃源新村1室0厅 5500元", "loc" : [ 121.488377804633, 31.23113867155927 ] }
{ "_id" : ObjectId("5c1c99cd4729d1aaa1bdbbef"), "hid" : 2, "title" : "陆家嘴板块,精装
设计一室一厅,可拎包入住诚意租。", "loc" : [ 121.51804613891443, 31.238878702131505 ] }
#查询上海中山公园附近2公里的房源,中山公园的坐标为:121.42261657004589,31.229111410235285
db.house.find({loc:{$near:[121.42261657004589,31.229111410235285],$maxDistance:2/111.12 }})
#查询结果:
{ "_id" : ObjectId("5c1c99cd4729d1aaa1bdbbf5"), "hid" : 8, "title" : "整租 · 中山公园品质小区,两房朝南厅朝南,家电家具精装*配", "loc" : [ 121.42038642151562, 31.225078800208653 ] }
{ "_id" : ObjectId("5c1c99cd4729d1aaa1bdbbf7"), "hid" : 10, "title" : "整租 · 2.3.4号中山公园地铁,背靠来福士,采光好,诚意出租", "loc" : [ 121.42063977421182, 31.221023374982042 ] }
{ "_id" : ObjectId("5c1c99cd4729d1aaa1bdbbf6"), "hid" : 9, "title" : "整租 · 近地铁2号线,精装1房1厅,高区朝南,享受阳光好房", "loc" : [ 121.42933310871683, 31.221943586471035 ] }