面试题答案
一键面试数据库设计
- 文档结构:假设POI文档结构如下:
{
"_id": ObjectId("..."),
"name": "POI名称",
"category": "类别",
"location": {
"type": "Point",
"coordinates": [经度, 纬度]
}
}
- 索引:为了高效查询,在
category
和location
字段上创建复合索引。在MongoDB中可以通过以下命令创建:
db.pois.createIndex({category: 1, location: "2dsphere"})
代码逻辑(以Python为例,使用pymongo库)
import pymongo
from bson.geospatial import Point
from pymongo.collection import Collection
def find_closest_pois(user_location: list, category: str, limit: int = 10):
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["your_database"]
pois_collection: Collection = db["pois"]
query = {
"category": category,
"location": {
"$near": {
"$geometry": {
"type": "Point",
"coordinates": user_location
},
"$maxDistance": 1000000 # 可根据实际情况调整最大距离
}
}
}
result = pois_collection.find(query).sort([("$distance", pymongo.ASCENDING)]).limit(limit)
closest_pois = list(result)
client.close()
return closest_pois
# 使用示例
user_location = [116.3975, 39.9087] # 用户当前位置 [经度, 纬度]
category = "餐厅"
closest_pois = find_closest_pois(user_location, category)
for poi in closest_pois:
print(poi)
上述代码实现了连接MongoDB数据库,查找指定类别且距离用户当前位置最近的前10个POI,并按距离升序返回。$near
操作符用于指定查询距离某个点最近的文档,$maxDistance
用于设置最大距离(单位为米,可按需调整)。