Search code examples
mongodboptimizationquery-optimizationmorphianosql

The fastest way to show Documents with certain property first in MongoDB


I have collections with huge amount of Documents on which I need to do custom search with various different queries. Each Document have boolean property. Let's call it "isInTop". I need to show Documents which have this property first in all queries. Yes. I can easy do sort in this field like:

.sort( { isInTop: -1 } );

And create proper index with field "isInTop" as last field in it. But this will be work slowly, as indexes in mongo works best with unique fields. So is there is solution to show Documents with field "isInTop" on top of each query?

I see two solutions here. First: set Documents wich need to be in top the _id from "future". As you know, ObjectId contains timestamp. So I can create ObjectId with timestamp from future and use natural order

Second: create separate collection for Ducuments wich need to be in top. And do queries in it first.

Is there is any other solutions for this problem? Which will work fater?

UPDATE I have done this issue with sorting on custom field which represent rank.


Solution

  • Using the _id field trick you mention has the problem that at some point in time you will reach the special time, and you can't change the _id field (without inserting a new document and removing the old one).

    Creating a special collection which just holds the ones you care about is probably the best option. It gives you the ability to logically (and to some extent, physically) separate the documents.

    Newly introduced in mongodb there is also support for a "sparse" index which may fulfill your needs as well. You could only set the "isInTop" field when you want it to be special, and then create a sparse index on it which would not have the problems you would normally have with a single indexed boolean field (in btrees).