MongoDB 高级索引
我们已经将以下文档插入到名为”users”的集合中,如下所示:
db.users.insert(
{
"address": {
"city": "Los Angeles",
"state": "California",
"pincode": "123"
},
"tags": [
"music",
"cricket",
"blogs"
],
"name": "Tom Benzamin"
}
)
上述文档包含一个 地址子文档 和一个 标签数组 。
索引数组字段
假设我们要基于用户的标签搜索用户文档。为此,我们将在集合中为标签数组创建一个索引。
在数组上创建索引会为其每个字段创建单独的索引项。所以在我们的案例中,当我们在标签数组上创建索引时,将会为其值音乐、板球和博客分别创建索引。
要在标签数组上创建索引,请使用以下代码:
>db.users.createIndex({"tags":1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
>
创建索引后,我们可以像这样在集合的标签字段上进行搜索 –
> db.users.find({tags:"cricket"}).pretty()
{
"_id" : ObjectId("5dd7c927f1dd4583e7103fdf"),
"address" : {
"city" : "Los Angeles",
"state" : "California",
"pincode" : "123"
},
"tags" : [
"music",
"cricket",
"blogs"
],
"name" : "Tom Benzamin"
}
>
为了验证是否使用了正确的索引,请使用以下 explain 命令 –
>db.users.find({tags:"cricket"}).explain()
这将给你以下结果 −
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "mydb.users",
"indexFilterSet" : false,
"parsedQuery" : {
"tags" : {
"$eq" : "cricket"
}
},
"queryHash" : "9D3B61A7",
"planCacheKey" : "04C9997B",
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"tags" : 1
},
"indexName" : "tags_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"tags" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"tags" : [
"[\"cricket\", \"cricket\"]"
]
}
}
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "Krishna",
"port" : 27017,
"version" : "4.2.1",
"gitVersion" : "edf6d45851c0b9ee15548f0f847df141764a317e"
},
"ok" : 1
}
>
上面的命令的结果是 “cursor” : “BtreeCursor tags_1″,这证实了正确的索引被使用。
索引子文档字段
假设我们想根据城市、州和邮政编码字段来搜索文档。由于所有这些字段都是地址子文档字段的一部分,我们将在子文档的所有字段上创建一个索引。
要在子文档的所有三个字段上创建索引,使用以下代码:
>db.users.createIndex({"address.city":1,"address.state":1,"address.pincode":1})
{
"numIndexesBefore" : 4,
"numIndexesAfter" : 4,
"note" : "all indexes already exist",
"ok" : 1
}
>
一旦索引被创建,我们可以使用这个索引来搜索任何子文档字段,如下所示:
> db.users.find({"address.city":"Los Angeles"}).pretty()
{
"_id" : ObjectId("5dd7c927f1dd4583e7103fdf"),
"address" : {
"city" : "Los Angeles",
"state" : "California",
"pincode" : "123"
},
"tags" : [
"music",
"cricket",
"blogs"
],
"name" : "Tom Benzamin"
}
请记住查询表达式必须遵循指定的索引顺序。因此,上面创建的索引将支持以下查询 –
>db.users.find({"address.city":"Los Angeles","address.state":"California"}).pretty()
{
"_id" : ObjectId("5dd7c927f1dd4583e7103fdf"),
"address" : {
"city" : "Los Angeles",
"state" : "California",
"pincode" : "123"
},
"tags" : [
"music",
"cricket",
"blogs"
],
"name" : "Tom Benzamin"
}
>