复合索引(Compound Indexes)指一个索引包含多个字段,用法和单键索引基本一致。使用复合索引时要注意字段的顺序,如下添加一个name和age的复合索引,name正序,age倒序,document首先按照name正序排序,然后name相同的document按age进行倒序排序。mongoDB中一个复合索引最多可以包含32个字段

1 准备测试数据

db.userinfos.insertMany([
   {_id:1, name: "张三", age: 23,level:10, ename: { firstname: "san", lastname: "zhang"}, roles: ["vip","gen" ]},
   {_id:2, name: "李四", age: 24,level:20, ename: { firstname: "si", lastname: "li"}, roles:[ "vip" ]},
   {_id:3, name: "王五", age: 25,level:30, ename: { firstname: "wu", lastname: "wang"}, roles: ["gen","vip" ]},
   {_id:4, name: "赵六", age: 26,level:40, ename: { firstname: "liu", lastname: "zhao"}, roles: ["gen"] },
   {_id:5, name: "田七", age: 27, ename: { firstname: "qi", lastname: "tian"}, address:'北京' },
   {_id:6, name: "周八", age: 28,roles:["gen"], address:'上海' }
]);

新建索引,用explain查看执行计划

//添加复合索引,name正序,age倒序
db.userinfos.createIndex({ "name": 1, "age": -1 })
//过滤条件为name,或包含name的查询会使用索引(索引的第一个字段),以下都会用到索引
db.userinfos.find({ name: '张三' }).explain()
db.userinfos.find({ name: "张三", level: 10 }).explain()
db.userinfos.find({ name: "张三", age: 23 }).explain()

//查询条件为age时,不会使用上边创建的索引,而是使用的全表扫描
db.userinfos.find({ age: 23 }).explain()

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐