索引
MongoDB支持的索引类型有:
-
单字段索引(Single Field)
-
支持所有数据类型中的单个字段索引
-
-
复合索引(Compound Index)
-
基于多个字段的索引,创建复合索引时要注意字段顺序与索引方向
-
-
多键索引(Multikey indexes)
-
针对属性包含数组数据的情况,MongoDB支持针对数组中每一个element创建索引。
-
-
全文索引(Text Index)
-
支持任意属性值为string或string数组元素的索引查询。
-
注意:一个集合仅支持最多一个Text Index,中文分词不理想,推荐Elasticsearch。
-
-
地理空间索引(Geospatial Index)
-
2dsphere索引,用于存储和查找球面上的点
-
2d索引,用于存储和查找平面上的点
-
-
哈希索引(Hashed Index)
-
针对属性的哈希值进行索引查询,当要使用Hashed index时,MongoDB能够自动的计算hash值,无需程序计算hash值。
-
hash index仅支持等于查询,不支持范围查询。
-
列举其中的单字段索引和地理空间索引
1、单字段索引
#单字段索引,1表示升序创建索引,-1表示降序创建索引
db.集合名.createIndex({"字段名":排序方式})
#示例,创建user集合,其中username字段设置索引
db.user.createIndex({"username":1})
db.user.insert({id:1,username:'zhangsan',age:20})
db.user.insert({id:2,username:'lisi',age:22})
#查看索引
db.user.getIndexes()
#查看索引大小,单位:字节
db.user.totalIndexSize()
#删除索引
db.user.dropIndex("username_1")
#或者,删除除了_id之外的索引
db.user.dropIndexes()
2、地理空间索引
MongoDB地理空间索引类型有:
-
Point(坐标点),coordinates必须是单个位置
-
MultiPoint(多个点),coordinates必须是位置数组
-
LineString(线形),coordinates必须是两个或多个位置的数组
-
MultiLineString(多行线形),coordinates必须是LineString坐标数组的数组
-
Polygon(多边形),coordinates成员必须是 LinearRing 坐标数组的数组,必须是闭环,也就是第一个和最后一个坐标点要相同。
-
MultiPolygon(多个多边形),coordinates成员必须是 Polygon 坐标数组的数组。
-
GeometryCollection(几何集合),geometries是任何一个对象的集合。
#2dsphere索引
db.集合名.createIndex({"字段名":"2dsphere"})
#示例,创建user集合,其中loc字段设置索引
db.user.createIndex({"loc":"2dsphere"})
db.user.insert({id:3,username:'wangwu',age:21,loc:{type:"Point",coordinates:[116.343847,40.060539]}})
db.user.insert({id:4,username:'zhaoliu',age:23,loc:{type:"Point",coordinates:[121.612112,31.034633]}})
#多边形索引类型示例
#为scpoe集合中的scpoe字段设置球面索引
db.scope.createIndex({"loc":"2dsphere"})
#为了便于理解,这里采用x、y坐标系的值来模拟快递员的作业范围
#coordinates格式必须是:[ [ [x,y],[x,y],[x,y] ] ]
db.scope.insert({
id: 1,
username: 'shkdy',
scpoe: {
type: "Polygon",
coordinates: [
[
[0,0],
[3,0],
[3,3],
[0,3],
[0,0]
]
]
}
})
db.scope.insert({
id: 2,
username: 'bjkdy',
scpoe: {
type: "Polygon",
coordinates: [
[
[- 3, 3],
[3, 3],
[3, - 3],
[- 3, - 3],
[- 3, 3]
]
]
}
})
#假设,现在有坐标点[-1,-1]用户下单,就需要查询到所在服务范围内的快递员
#$geoIntersects 查询与指定的几何图形(这里用的是点)相交的数据
#$geometry 指定几何图形
db.scope.find({
scpoe: {
$geoIntersects: {
$geometry: {
type: "Point",
coordinates: [-1, -1]
}
}
}
})
#显然,只能查询到【bjkdy】
#如何坐标点改为[1,1],就可以查询到这两个快递员
db.scope.find({
scpoe: {
$geoIntersects: {
$geometry: {
type: "Point",
coordinates: [1, 1]
}
}
}
})
UI客户端工具
官网:The Ultimate Client, IDE and GUI for MongoDB | Studio 3T
下载地址:Download Studio 3T for MongoDB | Windows, macOS & Linux