In the MongoDB Test library:
> 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. Create an index on the field info:
> Db.data.ensureIndex ({info:1});
Index query for 3.data tables:
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. Usage of the index:
The following query is available with the index of 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"});
You can use Query.explain () to view the use of the index:
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
}
But such a query will not work:
>db.data.find ({"info.city": "Beijing"}); Field part must be quoted
>db.data.find ({info.url: "..."});
Such a query statement can only use a similar composite index:
> Db.data.ensureIndex ({"Info.url": 1, "info.city": 1});
5. Combined Index
> Db.data.ensureIndex ({"Info.url": 1, "info.city": 1});
The index scan can be used even when querying, in contrast to the defined sort.
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
}
Indexing in MongoDB on documents embedded in a subdocument