Springboot使用mongo以及mongo的索引
在使用springboot项目中使用mongo时,编写完成后报错.找不到方法
2020-03-27T16:22:29,974 ERROR [http-nio-8122-exec-1] n.d.c.s.e.ClobExceptionAdvance: 系统异常
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): net.dgg.conference.mongoDao.ConferenceMongoDao.findById
at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:225)
at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:48)
at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58)
at com.sun.proxy.$Proxy181.findById(Unknown Source)
dao层是这样编写的
@Autowired
private MongoTemplate mongoTemplate;
@Override
public ConferenceEntity findById(Long id) {
return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), ConferenceEntity.class);
}
经过排查是因为将mongo的dao与mysql的dao放到了同一个包下.而且在启动类中的@MapperScan 扫描时全部扫描了,但是未找到该dao的对用xml.将dao分包放置即可.
在启动类的@MapperScan 注解中只扫描mysql对应的dao.
mongoDB中的索引
和mysql中的索引一样.增加索引可以大幅度提高查询效率.索引的本质上是一种数据结构.
可以理解为排好序的快速查找数据结构.
索引有两大功能: 1.排序 2.快速查找!
创建索引
db.collection.createIndex( <key and index type specification>, <options> )
MongoDB使用 createIndex() 方法来创建索引,在MongoDB的3.0.0 版本前创建索引方法为 db.collection.ensureIndex(),之后的版本使用了 db.collection.createIndex() 方法.
索引说明
1、索引类型
单列索引
db.collections.createIndex({field:1/-1})
说明:1代表asc升续索引,-1降序
db.collection.ensureIndex({'fleld.subfiled':1/-1});
说明: 为collection中文档的filed域下的subfiled域建索引
组合索引 db.collections.ensureIndex({filed1:1/-1,field2:1/-1})
说明: 1代表asc升续索引,-1降序,遵循“最左前缀”原则,查询条件只有filed1会走索引,如果查询条件只有filed2时不会走索引
复合索引 集合中的数组字段创建索引,复合索引不能当做片键、哈希索引
地理空间索引 db.collection.createIndex( { field : "2dsphere" } )
文本索引 db.collection.createIndex( { field: "text" } )
比较少用,不做说明
哈希索引 db.collection.createIndex({field:'hashed'})
说明:
1、哈希索引比普通查询效率比较高,可是哈希索引只列在单列,不支持多列创建哈希索引、唯一索引
2、只能满足字段完全匹配的查询,不支持范围的查询
管理索引
1、查询索引集合
db.collection.getIndexes()
2、查看集合索引大小
db.collection.totalIndexSize()
3、删除集合所有索引
db.collection.dropIndexes()
4、删除集合指定索引
db.collection.dropIndex("索引名称")
注:_id列的索引不会被删除
5、db.collection.find({}).explain()