面试题答案
一键面试- 连接到MongoDB:
- 使用合适的MongoDB客户端,例如
mongo
shell或者编程语言对应的驱动(如Python的pymongo
)连接到目标数据库。
- 使用合适的MongoDB客户端,例如
- 选择集合:
- 在
mongo
shell中,使用use <database_name>
选择数据库,然后使用db.<collection_name>
选择要操作的集合。例如:
- 在
use myDatabase;
var myCollection = db.myCollection;
- 构建复合地理空间索引:
- 地理位置信息需遵循GeoJSON格式,经纬度顺序为
[longitude, latitude]
。 - 使用
createIndex
方法创建复合索引,将地理位置字段设为地理空间索引类型("2dsphere"
),时间戳字段设为普通索引类型。例如:
- 地理位置信息需遵循GeoJSON格式,经纬度顺序为
myCollection.createIndex({ location: "2dsphere", timestamp: 1 });
这里location
是包含地理位置信息(经纬度)的字段名,timestamp
是时间戳字段名,1
表示升序索引,如果要降序则用-1
。
在编程语言驱动中操作类似,以pymongo
为例:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['myDatabase']
myCollection = db['myCollection']
myCollection.create_index([("location", "2dsphere"), ("timestamp", 1)])