MongoDB provides an interesting "multikey" feature that can automatically index arrays of an object's values.
但是通過explain,帶Multikeys的結果,開始不免有點奇怪.
看下測試例子:
向一個collection中save多條測試語句:
- db.fjx.save({name:"fjx", tags:['weather','hot','record','april']})
- db.fjx.save({name:"fjx1", tags:['weather1','hot','record','april']})
- db.fjx.save({name:"fjx2", tags:['weather2','hot','record','april']})
- db.fjx.save({name:"fjx3", tags:['weather3','hot','record','april']})
然後給tags數組建立索引!
- > db.fjx.find({tags:{$regex:"^weather"}}).explain()
- {
- "cursor" : "BtreeCursor tags_1 multi",
- "nscanned" : 4,
- "nscannedObjects" : 4,
- "n" : 4,
- "millis" : 0,
- "nYields" : 0,
- "nChunkSkips" : 0,
- "isMultiKey" : true,
- "indexOnly" : false,
- "indexBounds" : {
- "tags" : [
- [
- "weather",
- "weathes"
- ],
- [
- /^weather/,
- /^weather/
- ]
- ]
- }
- }
通過查詢 以weather開頭的explain, 它使用了multi索引. 我們再插入一條.
- db.fjx.save({name:"fjx4", tags:['weather4','weather5','record','april']})
- > db.fjx.find({tags:{$regex:"^weather"}}).explain()
- {
- "cursor" : "BtreeCursor tags_1 multi",
- "nscanned" : 5,
- "nscannedObjects" : 5,
- "n" : 4,
- "millis" : 0,
- "nYields" : 0,
- "nChunkSkips" : 0,
- "isMultiKey" : true,
- "indexOnly" : false,
- "indexBounds" : {
- "tags" : [
- [
- "weather",
- "weathes"
- ],
- [
- /^weather/,
- /^weather/
- ]
- ]
- }
- }
可以看出nscanned為5條, 而n為4條, 這點大家要注意下, 尤其在給數組建立索引的時候, 因為給數組建立索引它是給數組中的元素建立索引的, 所以它遍曆了所以符合索引的元素. 而n為成功搜尋的條數.