分析您的查询性能
我建议你使用mongoDB提供的.explain()来分析你的查询性能。
假设我们正在尝试执行此查询
db.inventory.find( { quantity: { $gte: 100, $lte: 200 } } )
这将是查询执行的结果
{ "_id" : 2, "item" : "f2", "type" : "food", "quantity" : 100 }
{ "_id" : 3, "item" : "p1", "type" : "paper", "quantity" : 200 }
{ "_id" : 4, "item" : "p2", "type" : "paper", "quantity" : 150 }
如果我们这样称呼.execution()
db.inventory.find(
{ quantity: { $gte: 100, $lte: 200 } }
).explain("executionStats")
它将返回以下结果:
{
"queryPlanner" : {
"plannerVersion" : 1,
...
"winningPlan" : {
"stage" : "COLLSCAN",
...
}
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 3,
"executionTimeMillis" : 0,
"totalKeysExamined" : 0,
"totalDocsExamined" : 10,
"executionStages" : {
"stage" : "COLLSCAN",
...
},
...
},
...
}
更多详情请见here
通过 _id 和索引搜索的效率如何
要回答您的问题,使用索引总是更有效。索引是一种特殊的数据结构,它以易于遍历的形式存储集合数据集的一小部分。 _id 是 MongoDB 提供的默认索引,这样可以提高效率。
没有索引,MongoDB 必须执行集合扫描,即扫描集合中的每个文档,以选择与查询语句匹配的文档。
所以,是的,使用像_id 这样的索引更好!
您也可以使用createIndex()创建自己的索引
db.collection.createIndex( <key and index type specification>, <options> )
优化您的 MongoDB 查询
如果您想优化查询,有多种方法可以做到这一点。
- 创建自定义索引以支持您的查询
- 限制查询结果的数量以减少网络需求
db.posts.find().sort( { timestamp : -1 } ).limit(10)
db.posts.find( {}, { timestamp : 1 , title : 1 , author : 1 , abstract : 1} ).sort( { timestamp : -1 } )
db.users.find().hint( { age: 1 } )