Index for sorting while using $in to query field containing an array

131 views Asked by At

I'm querying an array using $in operator and I'm also trying to sort results, but I keep getting this error:

too much data for sort() with no index. add an index or specify a smaller limit

I know that the sort is limited to 32 megabytes or you have to use an index. The problem is that I have a compound index on field that I'm querying and on field that I'm sorting on.

The collection:

{
    "a" : [ 1, 5, 7, 10 ],
    ... // other fields are not relevant for querying
}

The query looks like this:

db.mycol.find({ a: { $in : [ 1, 10, 19, 100, 2000 ] }}).sort({b : 1});

The $in query contains approx. 2000 IDs to match.

The index is

{
    "v" : 1,
    "key" : {
        "a" : 1,
        "b" : 1
    },
    "ns" : "db.mycol",
    "name" : "a_1_b_1",
    "background" : true
},

If I use explain() when doing the query without sort() I can see that MongoDB is using that index to perform the query, but it obviously cannot use that same index to perform the sort. I also tried to use a skip and limit, but if I use a skip that's too big I get the same error, probably because index is not used for sorting.

If i create an index only on field b MongoDB will happily sort the data for me. But what I really want is to perform a search on indexed array field and sort the data.

I looked at the documentation but I couldn't find anything helpful. Did I encounter a bug in MongoDB or I'm doing something wrong?

0

There are 0 answers