MongoDB基于标签的$all查询优化:指定遍历少标签集的方法
让MongoDB优先遍历小众标签优化$all查询速度
- 先给
tags字段建多键索引,这是优化的前提:db.posts.createIndex({tags: 1}) - 正常情况下MongoDB会自动选文档量更少的标签(也就是
few_posts_have_this)作为查询起点,但如果它没这么做,直接重构查询强制优先匹配小众标签:
把原来的查询:
改成:db.posts.find({'tags': {'$all': ['most_posts_have_this', 'few_posts_have_this']}})
这样查询会先把带db.posts.find({ '$and': [ {'tags': 'few_posts_have_this'}, {'tags': {'$all': ['most_posts_have_this', 'few_posts_have_this']}} ] })few_posts_have_this的少量文档筛出来,再在这个小范围里检查是否同时有另一个标签,不用扫大量带most_posts_have_this的帖子。 - 可以用
explain("executionStats")查看查询计划,确认是不是真的优先走了小众标签的索引:db.posts.find(...).explain("executionStats")
内容的提问来源于stack exchange,提问作者Noah McIlraith
相关产品推荐
相关产品推荐

