首页 > 代码库 > mongodb中在嵌套子文档的文档上面建立索引
mongodb中在嵌套子文档的文档上面建立索引
在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
}
mongodb中在嵌套子文档的文档上面建立索引