推荐工具
› RoboMongo
推荐书目
› 50 Tips and Tricks for MongoDB Developers
Related Blogs
› Snail in a Turtleneck
mikulch
V2EX  ›  MongoDB

关于 MongoDB/mysql 数据库复合索引原理的一个小问题。

  •  
  •   mikulch · Nov 7, 2016 · 4189 views
    This topic created in 3648 days ago, the information mentioned may be changed or developed.

    最近买了一本 MongoDB 权威指南第二版,看到大概第五章左右。

    书里面提到一个概念, MongoDB 中建立了复合索引如{username:1,age:1,email:1}以后,

    使用{usernam:lily,age:20}的查询可以被索引优化,而使用{age:20}或者{age:20,email:[email protected]}的查询却不能被索引所优化。

    总而言之,必须使用索引前缀或者完全使用索引覆盖的查询才能被优化。

    想了一晚上,实在想不明白为什么。

    有没有高人帮忙用简明易懂的话告诉我一下其中的原理。

    谢谢了!

    6 replies  •  2016-11-07 16:41:39 +08:00
    mikulch
    mikulch
    OP
    Nov 7, 2016
    1
    顺便为啥我昨晚 1 点发的帖子被吞了??

    ???
    yidinghe
    yidinghe
    PRO
    Nov 7, 2016 via Android
    2
    我猜原因是,索引的原理是二叉树,复合索引的 key 不过是各个 key 拼起来而已,所以查找的时候的 key 如果是按照索引规则来的(哪怕只是前缀),也能在树中进行查找,否则就不行了。
    rahuahua
    rahuahua
    Nov 7, 2016
    3
    看看 B(各种变形)的数据结构,然后想想在你建的索引下{age:20}这个查询能不能做到快速查询
    rahuahua
    rahuahua
    Nov 7, 2016
    4
    @rahuahua 更正下
    看看 B 树(以及各种变形)的数据结构,然后想想在你建的索引下{age:20}这个查询能不能做到快速查询
    ihuotui
    ihuotui
    Nov 7, 2016
    5
    @yidinghe 是的
    pippo
    pippo
    Nov 7, 2016
    6
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4476 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 09:45 · PVG 17:45 · LAX 01:45 · JFK 04:45
    ♥ Do have faith in what you're doing.