MongoDB读取数据的方法
MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录。
什么是索引
索引是特殊的数据结构,索引存储在一个易于遍历读取的数据集合中,索引是对数据库表中一列或多列的值进行排序的一种结构
createIndex()方法
MongoDB使用 createIndex() 方法来创建索引。
在 3.0.0 版本前创建索引方法为 db.collection.ensureIndex(),之后的版本使用了 db.collection.createIndex() 方法,ensureIndex() 还能用,但只是 createIndex() 的别名。
语法:
db .collection.createIndex ( keys , options )
语法中 Key 值为你要创建的索引字段,1 为指定按升序创建索引,如果你想按降序来创建索引指定为 -1 即可
createIndex() 接收可选参数,可选参数列表如下:
Parameter Type Description background Boolean 建索引过程会阻塞其它数据库操作,background可指定以后台方式创建索引,即增加 "background" 可选参数。 "background" 默认值为 false 。 unique Boolean 建立的索引是否唯一。指定为true创建唯一索引。默认值为 false . name string 索引的名称。如果未指定,MongoDB的通过连接索引的字段名和排序顺序生成一个索引名称。 dropDups Boolean 3.0+版本已废弃。 在建立唯一索引时是否删除重复记录,指定 true 创建唯一索引。默认值为 false . sparse Boolean 对文档中不存在的字段数据不启用索引;这个参数需要特别注意,如果设置为true的话,在索引字段中不会查询出不包含对应字段的文档.。默认值为 false . expireAfterSeconds integer 指定一个以秒为单位的数值,完成 TTL设定,设定集合的生存时间。 v index version 索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。 weights document 索引权重值,数值在 1 到 99,999 之间,表示该索引相对于其他索引字段的得分权重。 default_language string 对于文本索引,该参数决定了停用词及词干和词器的规则的列表。 默认为英语 language_override string 对于文本索引,该参数指定了包含在文档中的字段名,语言覆盖默认的language,默认值为 language.createIndex实例应用
首先先构造测试数据和测试表格:
使用Java构造表格--->因为循环创建decoment加入List插入集合补会(尴尬)所以使用的是mongodb循环插入--->但是10W条数据只有1000条
package mongodbtest;
?
import com. mongodb. MongoClient;
import com. mongodb. client. MongoCollection;
import com. mongodb. client. MongoDatabase;
import org. bson. Document;
?
import java. util. ArrayList;
import java. util. List;
?
/**
* 1、利用Java连接MongoDB
* 2、连接数据库practice
* 3、创建集合:practiceindex
* 4、向集合中插入10w条记录
* 5、创建索引
* 6、利用索引查询
* @since JDK 1.8
* @date 2021/7/1
* @author Lucifer
*/
public class MongoDBTestNo1 {
?
/*定义连接需要用到的属性*/
private static String MONGO_HOST = "localhost";
private static Integer MONGO_PORT = 27017;
private static final String MONGO_DB_NAME = "practice";
private static final String GATHER_NAME = "practiceindex";
?
public static String getMongoHost() {
return MONGO_HOST;
}
?
public static Integer getMongoPort() {
return MONGO_PORT;
}
?
public static void setMongoHost( String mongoHost) {
MONGO_HOST = mongoHost;
}
?
public static void setMongoPort( Integer mongoPort) {
MONGO_PORT = mongoPort;
}
?
/**
* 访问MongoDB服务,连接到指定的数据库
* @param mongo_host
* @param mongo_port
* @return
*/
public static MongoDatabase connection( String mongo_host, Integer mongo_port){
?
//使用MongoClient类创建Mongo连接服务
MongoClient mongoClient = new MongoClient( mongo_host, mongo_port);
?
//使用服务引用连接到数据库
MongoDatabase mongoDatabase = mongoClient. getDatabase( MONGO_DB_NAME);
System. out. println( "Connect to database successfully!!!");
?
//返回Mongodatabase对象
return mongoDatabase;
?
}
?
/**
* 创建集合
* @return
*/
public static String createCollection(){
?
//访问到指定的域名和端口
MongoDatabase mongoDatabase = MongoDBTestNo1. connection( MONGO_HOST, MONGO_PORT);
?
//使用mongoDatabase类创建集合
mongoDatabase. createCollection( GATHER_NAME);
System. out. println( "Create collection successfully!!!");
?
//结束方法
return null;
?
}
?
/**
* 选择集合获取集合信息
* @return
*/
public static MongoCollection < Document > getCollection(){
?
//创建Mongodatabase引用
MongoDatabase mongoDatabase = null; //一开始要初始化为空
?
//调用创建集合方法
MongoDBTestNo1. createCollection();
?
//使用返回值类型获取集合名称
MongoCollection < Document > collection = mongoDatabase. getCollection( GATHER_NAME);
System. out. println( "Choose collection successfully!!!");
?
//返回集合对象
return collection;
?
}
}
在mongodb上用循环插入数据:
for (var i = 0 ; i < 100000 ; i ++ ){
db .getCollection ( "practiceindex" ) .insert (
{
"onumber" :i ,
"date" : ‘2021-07-01‘ ,
"cname" : ‘Jun‘ +i ,
"items" : [
{
"ino" :i ,
"quantity" :i ,
"price" : 4.4
} ,
{
"ino" :i + 1 ,
"quantity" :i + 1 ,
"price" : 6.0
}
]
}
)
}
//花费 : 42.993s
默认索引
存储在MongoDB集合中的每个文档(document)都有一个默认的主键“ id“,在添加新的文档时,没有指定“ id“值时,MongoDB会创建一个ObjectId值,并创建会自动创建一个索引在“ id“键上,默认索引的名称是” id_“,并无法删除,如下面的命令查看:
db .getCollection () .getIndexes ()创建单列索引
// 查看索引信息
//返回一个数组,该数组保存标识和描述集合上现有索引的文档列表,可以查看我们是否有对某个集合创建索引,并创建哪些索引,方便我们管理。
对文档单个字段创建索引或者对内嵌文档的单个字段创建索引
语法:
db .getCollection () .createIndex (
{
field : boolean
}
)
boolean:对于某个域的升序索引,指定一个值为1;对于降序的索引,指定一个值为-1
实例:
db .getCollection ( "practiceindex" ) .createIndex (
{
cname : 1
}
)
对practiceindex集合创建了cname索引,默认的索引名称是”cname_1“
使用同一个语句检测查询效率的提升
测试有建索引和没建索引在1000000条文档执行查询的效率怎么样,先使用explain()函数
几个参数:
n:当前查询返回的文档数量
millis:当前查询所需时间,毫秒数
indexBounds:当前查询具体使用的索引
对集合practiceindex没建索引时查询条件为‘Jun999‘的时间
db .getCollection ( ‘practiceindex‘ ) .find ({cname : ‘Jun99999‘ }) .explain ()
建立索引以后查询数据消耗的时间:
查询和排序的组合使用
查询集合cname大于Jun100的文档并对onumber进行降序排序
db .getCollection ( "practiceindex" ) .find (
{
cname : {$gt : 100 }
}
) .sort (
{
onumber : 1
}
) .explain ()
//对这个域进行建立索引以后加入到内存的内容会减少所以查询时间会略微提升
创建组合索引
同时对多个键创建组合索引
语法:
db .getCollection.createIndex ({field1:boolean , field2:boolean })
注意:在MongoDB中依次建立索引和建立组合索引并不是一样的。
查询时会用到的索引种类:
key.cname
key.cname,key.onumber
由上述例子可以知道:
可以使用cname作为索引
也可以使用cname和onumber作为索引
不能使用onumber作为单独的索引
具体例子如下
db .getCollection ( "practiceindex" ) .find ({ "onumber" : 2000 }) .explain ()
//这个查询就没有用到索引加速
内嵌文档的索引
对内嵌文档创建索引时,跟基本文档创建索引一样
语法:--->通过"."来指明内嵌文档的路径
单例内嵌文档:
db .getCollection ( "practiceindex" ) .createIndex ({ "items.info" : 1 })
对practiceindex集合下内嵌的items集合的info域创建索引
组合的内嵌文档的索引的创建
db .getCollection ( "practiceindex" ) .createIndex ({ "items.info" : 1 , "items. quantity" : - 1 })
删除索引
针对集合中具体的索引进行删除语法:
db .getCollection () .dropIndex (index_name )
获取集合中索引名称的方法:
db .getCollection () .getIndexes ()针对集合中的所有索引进行删除
语法:
db .getCollection () .dropIndexes ()
dropIndexes方法指定集合的具体索引的删除--->使用runCommand方法
db .runCommand (
{
"dropIndexes" : "practiceindex" ,
"index" : "cname_1_onumber_-1"
}
)
createIndex() 接收可选参数,可选参数列表如下:
Parameter Type Description background Boolean 建索引过程会阻塞其它数据库操作,background可指定以后台方式创建索引,即增加 "background" 可选参数。 "background" 默认值为 false 。 unique Boolean 建立的索引是否唯一。指定为true创建唯一索引。默认值为 false . name string 索引的名称。如果未指定,MongoDB的通过连接索引的字段名和排序顺序生成一个索引名称。 dropDups Boolean 3.0+版本已废弃。 在建立唯一索引时是否删除重复记录,指定 true 创建唯一索引。默认值为 false . sparse Boolean 对文档中不存在的字段数据不启用索引;这个参数需要特别注意,如果设置为true的话,在索引字段中不会查询出不包含对应字段的文档.。默认值为 false . expireAfterSeconds integer 指定一个以秒为单位的数值,完成 TTL设定,设定集合的生存时间。 v index version 索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。 weights document 索引权重值,数值在 1 到 99,999 之间,表示该索引相对于其他索引字段的得分权重。 default_language string 对于文本索引,该参数决定了停用词及词干和词器的规则的列表。 默认为英语 language_override string 对于文本索引,该参数指定了包含在文档中的字段名,语言覆盖默认的language,默认值为 language.后台创建索引实例
db .getCollection () .createIndex ({ open : 1 , close : 1 } , {background : true })
在创建索引时加 background:true 的选项,让创建工作在后台执行
7.1MongoDB之索引
标签:实例 comment 访问 efault 域名 文本 mic loading nis