To have efficient sorting in mongo is it necessary to change the _id field?
I have a document with only about 200 elements in it. But I am still getting a very slow response just by querying it like:
Product.order_by([:name, :asc]).limit(20)
I do have an index on name which开发者_JS百科 I have verified exists in the mongo shell. Is the only way to return efficiently sorted results to change they _id value to something like
"#{name}_#{random_id}"
Short answer: absolutely not. Long answer: let's make sure the query is using your index (not just that the index exists).
Our query:
This does not use an index (in this case, because it does not exist)
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" : {
}
Let's prove it
db.products.getIndexes()
[
{
"name" : "_id_",
"ns" : "project_development.products",
"key" : {
"_id" : 1
}
}
]
Create the index
db.products.ensureIndex({name:1});
Now when we explain the query:
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
}
]
]
}
}
精彩评论