Optimal Compound Indexes for $exists : true (sparse indexes)

谁说我不能喝 提交于 2019-12-04 11:44:07

What you do not seem to be understanding here is that $exists cannot "grab" an index in any way, even where sparse. As the documentation itself says:

"If a sparse index would result in an incomplete result set for queries and sort operations, MongoDB will not use that index"

The example given in those pages is an { "$exists": false } query. But the reverse logical condition does not make any difference here.

In order to get the "full benefit" of a "sparse" index then you need to consider the "type" of data it holds and query appropriately.

For numeric, something like:

db.collection.find({ "a": "foobar", "b": { "$gte": -9999, "$lte": 9999 } })

Which uses an index, and the sparse one. Or for text based:

db.collection.find({ "a": "foobar", "b": /.+/ })

Which will also use the sparse index and only look at those where "b" was defined.

For "arrays" then "be careful". As the value being looked at is probably one of the above unless you did this:

db.collection.insert({ "a": 1, "b": [[]] })

Where then this is okay:

db.ab.find({ "a": 1, "b": { "$type": 4 } })

But is not really going to use the "sparse" index either for the same reasons $exists won`t work here.

So you need to understand what the terms mean here are, and "query appropriately" in order to use the index definitions that you create if you expect the maximum performance.

These are clear examples you can test for yourself and see the results are true. I do wish the core documentation was clearer on these points, but I am also aware many have tried to contribute ( and have produced excellent explainations ) but none of these have been included to date.

Guess that is why you are asking here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!