1. 程式人生 > >mongoTemplate count index(索引)

mongoTemplate count index(索引)

spring整合mongo給出的mongoTemplate在進行count的時候是不使用索引的(find可以)!!!!!雖然mongo執行語句時會自動幫我們進行優化,但可能並不是我們想要使用的那個索引

  1. 表字段

  2. 加上索引

  3. 使用客戶端進行查詢 db.play_following.find({"obj_type":"game","channel":"hao"}).hint("channel_index").count() (hint表示使用某一個索引) 查詢結果(1.6s內返回)

  4. 使用mongoTemplate進行查詢(60s返回,機器效能也有關係) 跟蹤原始碼可以看到在count的時候先進行了query轉化為DBObject的動作,但是我們的hint並沒有被其加以轉化,所以我們索引並沒有被使用

  5. 解決辦法:使用mongo原生的驅動(以下為參考): mongoTemplate.getDb().getCollection(PlayerFollowingPO.class.getAnnotation(Document.class).collection()).count(countDBObject, new DBCollectionCountOptions().hintString(index))