帮助中心/最新通知

质量为本、客户为根、勇于拼搏、务实创新

< 返回文章列表

【服务器相关】MongoDB基础知识 之 索引类型介绍

发表时间:2025-09-24 16:09:00 小编:主机乐-Yutio
可以看到通过文本索引可以查到包含测试关键字的数据。
**注意:**可以根据自己需要创建复合文本索引。

2dsphere索引

创建测试数据


db.places.insert(
{
loc : { type: “Point”, coordinates: [ 116.291226, 39.981198 ] },
name: “火器营桥”,
category : “火器营桥”
}
)

db.places.insert(
{
loc : { type: “Point”, coordinates: [ 116.281452, 39.914226 ] },
name: “五棵松”,
category : “五棵松”
}
)

db.places.insert(
{
loc : { type: “Point”, coordinates: [ 116.378038, 39.851467 ] },
name: “角门西”,
category : “角门西”
}
)

db.places.insert(
{
loc : { type: “Point”, coordinates: [ 116.467833, 39.881581 ] },
name: “潘家园”,
category : “潘家园”
}
)

db.places.insert(
{
loc : { type: “Point”, coordinates: [ 116.468264, 39.914766 ] },
name: “国贸”,
category : “国贸”
}
)

db.places.insert(
{
loc : { type: “Point”, coordinates: [ 116.46618, 39.960213 ] },
name: “三元桥”,
category : “三元桥”
}
)

db.places.insert(
{
loc : { type: “Point”, coordinates: [ 116.400064, 40.007827 ] },
name: “奥林匹克森林公园”,
category : “奥林匹克森林公园”
}
)

添加2dsphere索引

利用2dsphere索引查询多边形里的点

凤凰岭
[116.098234,40.110569]
天安门
[116.405239,39.913839]
四惠桥
[116.494351,39.912068]
望京
[116.494494,40.004594]


handong1:PRIMARY> db.places.find( { loc :
… { $geoWithin :
… { $geometry :
… { type : “Polygon” ,
… coordinates : [ [
… [116.098234,40.110569] ,
… [116.405239,39.913839] ,
… [116.494351,39.912068] ,
… [116.494494,40.004594] ,
… [116.098234,40.110569]
… ] ]
… } } } } )
{ “_id” : ObjectId(“60a4c950d4211a77d22bf7f8”), “loc” : { “type” : “Point”, “coordinates” : [ 116.400064, 40.007827 ] }, “name” : “奥林匹克森林公园”, “category” : “奥林匹克森林公园” }
{ “_id” : ObjectId(“60a4c94fd4211a77d22bf7f7”), “loc” : { “type” : “Point”, “coordinates” : [ 116.46618, 39.960213 ] }, “name” : “三元桥”, “category” : “三元桥” }
{ “_id” : ObjectId(“60a4c94fd4211a77d22bf7f6”), “loc” : { “type” : “Point”, “coordinates” : [ 116.468264, 39.914766 ] }, “name” : “国贸”, “category” : “国贸” }

可以看到把集合中包含在指定四边形里的点,全部列了出来。

利用2dsphere索引查询球体上定义的圆内的点


handong1:PRIMARY> db.places.find( { loc :
… { $geoWithin :
… { $centerSphere :
…[ [ 116.439518, 39.954751 ] , 2/3963.2 ]
… } } } )
{ “_id” : ObjectId(“60a4c94fd4211a77d22bf7f7”), “loc” : { “type” : “Point”, “coordinates” : [ 116.46618, 39.960213 ] }, “name” : “三元桥”, “category” : “三元桥” }

返回所有半径为经度 116.439518 E 和纬度 39.954751 N 的2英里内坐标。示例将2英里的距离转换为弧度,通过除以地球近似的赤道半径3963.2英里。

2d索引

在以下情况下使用2d索引:

  • 您的数据库具有来自MongoDB 2.2或更早版本的旧版旧版坐标对。
  • 您不打算将任何位置数据存储为GeoJSON对象。

哈希索引

要创建hashed索引,请指定 hashed 作为索引键的值,如下例所示:

注意事项
  • MongoDB支持任何单个字段的 hashed 索引。hashing函数折叠嵌入的文档并计算整个值的hash值,但不支持多键(即.数组)索引。
  • 您不能创建具有hashed索引字段的复合索引,也不能在索引上指定唯一约束hashed;但是,您可以hashed在同一字段上创建索引和升序/降序(即非哈希)索引:MongoDB将对范围查询使用标量索引。
正在回复: 取消回复

发表评论

暂无评论
成为第一个留下见解的人

联系我们
返回顶部