日期:2014-05-16  浏览次数:20381 次

mongodb 使用索引优化查询

数据库 > tmp

集合 > app_down

?

> use tmp

switched to db tmp

R:使用tmp数据库

?

> db.createCollection("app_down");

{ "ok" : 1 }

R:创建集合

?

> db.app_down.save({"app_id":1002,"count_down":33,"stat_date":"2014-01-01"});

> db.app_down.save({"app_id":1102,"count_down":33,"stat_date":"2014-01-02"});

> db.app_down.save({"app_id":1100,"count_down":33,"stat_date":"2014-01-02"});

R:模拟测试数据

?

> db.app_down.find();

{ "_id" : ObjectId("534f72c0c7f347b9e5b44efc"), "app_id" : 1002, "count_down" : 33, "stat_date" : "2014-01-01" }

{ "_id" : ObjectId("534f72cac7f347b9e5b44efd"), "app_id" : 1102, "count_down" : 33, "stat_date" : "2014-01-02" }

{ "_id" : ObjectId("534f72cec7f347b9e5b44efe"), "app_id" : 1100, "count_down" : 33, "stat_date" : "2014-01-02" }

R:查询所有数据

?

> db.app_down.getIndexes();

[

{

"v" : 1,

"key" : {

"_id" : 1

},

"ns" : "tmp.app_down",

"name" : "_id_"

}

]

R: 查询集合索引列表,插入数据时默认会给_id创建"升序"索引,在find()中不排序情况下默认是按照_id"升序" 排序

?

> db.app_down.find({app_id:1100}).explain();

{

"cursor" : "BasicCursor",

"isMultiKey" : false,

"n" : 1,

"nscannedObjects" : 3,

"nscanned" : 3,

"nscannedObjectsAllPlans" : 3,

"nscannedAllPlans" : 3,

"scanAndOrder" : false,

"indexOnly" : false,

"nYields" : 0,

"nChunkSkips" : 0,

"millis" : 0,

"indexBounds" : {

?

},

"server" : "tts-0001:27017"

}

R:查询分析 cursor索引类型,BasicCursor没有使用索引,

?

> db.app_down.ensureIndex({app_id:1});

R:给字段app_id创建升序索引

?

> db.app_down.getIndexes();

[

{

"v" : 1,

"key" : {

"_id" : 1

},

"ns" : "tmp.app_down",

"name" : "_id_"

},

{

"v" : 1,

"key" : {

"app_id" : 1

},

"n