MongoDB Multikeys索引


MongoDB provides an interesting "multikey" feature that can automatically index arrays of an object's values. 

但是通过explain,带Multikeys的结果,开始不免有点奇怪.

看下测试例子:
向一个collection中save多条测试语句:
  1. db.fjx.save({name:"fjx", tags:['weather','hot','record','april']})  
  2. db.fjx.save({name:"fjx1", tags:['weather1','hot','record','april']})  
  3. db.fjx.save({name:"fjx2", tags:['weather2','hot','record','april']})  
  4. db.fjx.save({name:"fjx3", tags:['weather3','hot','record','april']})  
然后给tags数组建立索引!
  1. > db.fjx.find({tags:{$regex:"^weather"}}).explain()  
  2. {  
  3.     "cursor" : "BtreeCursor tags_1 multi",  
  4.     "nscanned" : 4,  
  5.     "nscannedObjects" : 4,  
  6.     "n" : 4,  
  7.     "millis" : 0,  
  8.     "nYields" : 0,  
  9.     "nChunkSkips" : 0,  
  10.     "isMultiKey" : true,  
  11.     "indexOnly" : false,  
  12.     "indexBounds" : {  
  13.         "tags" : [  
  14.             [  
  15.                 "weather",  
  16.                 "weathes"  
  17.             ],  
  18.             [  
  19.                 /^weather/,  
  20.                 /^weather/  
  21.             ]  
  22.         ]  
  23.     }  
  24. }  
通过查询 以weather开头的explain, 它使用了multi索引. 我们再插入一条.
  1. db.fjx.save({name:"fjx4", tags:['weather4','weather5','record','april']})  
  2. > db.fjx.find({tags:{$regex:"^weather"}}).explain()  
  3. {  
  4.     "cursor" : "BtreeCursor tags_1 multi",  
  5.     "nscanned" : 5,  
  6.     "nscannedObjects" : 5,  
  7.     "n" : 4,  
  8.     "millis" : 0,  
  9.     "nYields" : 0,  
  10.     "nChunkSkips" : 0,  
  11.     "isMultiKey" : true,  
  12.     "indexOnly" : false,  
  13.     "indexBounds" : {  
  14.         "tags" : [  
  15.             [  
  16.                 "weather",  
  17.                 "weathes"  
  18.             ],  
  19.             [  
  20.                 /^weather/,  
  21.                 /^weather/  
  22.             ]  
  23.         ]  
  24.     }  
  25. }  

可以看出nscanned为5条, 而n为4条, 这点大家要注意下, 尤其在给数组建立索引的时候, 因为给数组建立索引它是给数组中的元素建立索引的, 所以它遍历了所以符合索引的元素. 而n为成功搜索的条数.

相关内容