Question

I am trying to use only the index while reading data from a collection in MongoDB, because I have some big documents, while for this query I need only one field.

It turns out that I cannot have indexOnly = true if the index is a multiKey index.

Here is the test I made:

db.test.drop()
db.test.insert({a:1})
db.test.ensureIndex({a:1})
db.test.find({a:1}, {_id:0, a:1}).explain()

-> indexOnly = true, isMultiKey = false

db.test.insert({a : [2,3]})
db.test.find({a:1}, {_id:0, a:1}).explain()

-> indexOnly = false, isMultiKey = true

The documentation mentions some limitations of the multikey indexes, but not this one. Does anybody have an idea how to use both multikey and indexonly?

Was it helpful?

Solution

From: http://docs.mongodb.org/manual/tutorial/create-indexes-to-support-queries/#create-indexes-that-support-covered-queries

An index cannot cover a query if any of the indexed fields in any of the documents in the collection includes an array. If an indexed field is an array, the index becomes a multi-key index index and cannot support a covered query.

You are inserting an array into your test collection, so when mongo is creating the index, it has to create a MultiKey index (it means it is creating the index for each item of the array).

OTHER TIPS

Note that when you have an indexOnly query, the returned document must be synthesized out of the information in the index only. That means that without looking at the document, the correct exact document must be returned.

In case of multiKey index, the query doesn't know whether to return
{ "a" : 1 }
or
{ "a" : [ 1 ] }

All it can tell is that "a" has value 1 and index is of type multiKey. It needs to look in the document to tell whether the type of "a" is an array or number.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top