要在mongo中进行有效排序,是否需要更改_id字段?

时间:2011-10-06 13:58:38

标签: ruby-on-rails ruby mongodb mongoid

我的文档中只包含大约200个元素。但是我只是通过查询它来得到一个非常慢的响应:

Product.order_by([:name, :asc]).limit(20)

我确实有一个名称的索引,我已经验证了mongo shell中存在的名称。是有效返回有效排序结果的唯一方法是将它们的值改为

"#{name}_#{random_id}"

1 个答案:

答案 0 :(得分:2)

简短回答:绝对没有。 答案很长:让我们确保查询正在使用您的索引(而不仅仅是索引存在)。

我们的查询:

这不使用索引(在这种情况下,因为它不存在)

db.products.find().sort( { name: -1}).explain()
{
    "cursor" : "BasicCursor",
    "nscanned" : 1042,
    "nscannedObjects" : 1042,
    "n" : 1042,
    "scanAndOrder" : true,
    "millis" : 5,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {
        }

让我们证明一下

db.products.getIndexes()
[
    {
        "name" : "_id_",
        "ns" : "project_development.products",
        "key" : {
            "_id" : 1
        }
    }
]

创建索引

db.products.ensureIndex({name:1});

现在,当我们解释查询时:

db.products.find().sort( { name: -1}).explain()
{
    "cursor" : "BtreeCursor name reverse",
    "nscanned" : 1042,
    "nscannedObjects" : 1042,
    "n" : 1042,
    "millis" : 2,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {
        "name" : [
            [
                {
                    "$maxElement" : 1
                },
                {
                    "$minElement" : 1
                }
            ]
        ]
    }
}