您好,登錄后才能下訂單哦!
在mongodb的test庫:
> db.data.insert({name:"1616",info:{url:"http://www.1616.net/",city:"beijing"}});
> db.data.insert({name:"hao123",info:{url:"http://www.hao123.com/",city:"beijing"}});
> db.data.insert({name:"ll4la",info:{url:"http://www.114la.com/",city:"dongguan"}});
2.對字段 info 創建索引:
> db.data.ensureIndex({info: 1});
3.data表的索引查詢:
rs0:PRIMARY> db.data.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.data"
},
{
"v" : 1,
"key" : {
"info" : 1
},
"name" : "info_1",
"ns" : "test.data"
}
]
4.索引的用法:
以下查詢是可以用到info的索引的:
>db.data.find({info: {url:"http://www.1616.net/", city:"beijing"}});
>db.data.find({info: {url:"http://www.1616.net/"} });
>db.data.find({info: {city:"beijing"});
可以使用query.explain()查看索引的使用:
rs0:PRIMARY> db.data.find({info: {city:"beijing"}}).explain()
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.data",
"indexFilterSet" : false,
"parsedQuery" : {
"info" : {
"$eq" : {
"city" : "beijing"
}
}
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"info" : 1
},
"indexName" : "info_1",
"isMultiKey" : false,
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 1,
"direction" : "forward",
"indexBounds" : {
"info" : [
"[{ city: \"beijing\" }, { city: \"beijing\" }]"
]
}
}
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "mycentos.WORKGROUP",
"port" : 27017,
"version" : "3.2.8",
"gitVersion" : "ed70e33130c977bda0024c125b56d159573dbaf0"
},
"ok" : 1
}
但是這樣的查詢就不行:
>db.data.find({"info.city":"beijing"}); //字段部分必須加引號
>db.data.find({info.url:"..."});
這樣的查詢語句,只能使用類似的組合索引:
> db.data.ensureIndex({"info.url":1, "info.city":1});
5.組合索引
> db.data.ensureIndex({"info.url":1, "info.city":1});
即使查詢時,與定義的排序相反,也是可以使用索引掃描的。
rs0:PRIMARY> db.data.find({"info.url": /http:*/i}).sort({"info.url": -1, "info.city":-1}).explain()
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.data",
"indexFilterSet" : false,
"parsedQuery" : {
"info.url" : /http:*/i
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"filter" : {
"info.url" : /http:*/i
},
"keyPattern" : {
"info.url" : 1,
"info.city" : 1
},
"indexName" : "info.url_1_info.city_1",
"isMultiKey" : false,
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 1,
"direction" : "backward",
"indexBounds" : {
"info.url" : [
"[/http:*/i, /http:*/i]",
"({}, \"\"]"
],
"info.city" : [
"[MaxKey, MinKey]"
]
}
}
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "mycentos.WORKGROUP",
"port" : 27017,
"version" : "3.2.8",
"gitVersion" : "ed70e33130c977bda0024c125b56d159573dbaf0"
},
"ok" : 1
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。