单字段索引
在本页面
本文档描述单个字段上的升序/降序索引。
Diagram of an index on the ``score`` field (ascending).
假设一个 records的集合,包含类似于如下所示的文档:
{
"_id": ObjectId("570c04a4ad233577f97dc459"),
"score": 1034,
"location": { state: "NY", city: "New York" }
}
下面的操作在records集合的score字段上创建一个升序索引:
db.records.createIndex( { score: 1 } )
创建的索引将支持在字段
score
上选择查询,例如:db.records.find( { score: 2 } )
db.records.find( { score: { $gt: 10 } } )
可以在嵌入文档中的字段上创建索引,就像索引文档中的顶级字段一样。嵌入字段上的索引不同于嵌入文档上的索引,它包含了完整的内容,直到索引中嵌入文档的最大“索引大小”为止。相反,嵌入字段上的索引允许您使用“点表示法”来内省嵌入的文档。
考虑一个名为**“records”**的集合,它包含类似于以下示例文档的文档:
{
"_id": ObjectId("570c04a4ad233577f97dc459"),
"score": 1034,
"location": { state: "NY", city: "New York" }
}
以下操作在**"location.state"** 字段上创建索引:
db.records.createIndex( { "location.state": 1 } )
创建的索引将支持选择字段**"location.state"**的查询。,例如:
db.records.find( { "location.state": "CA" } )
db.records.find( { "location.city": "Albany", "location.state": "NY" } )
您还可以在整个内嵌文档上创建索引。
考虑一个名为**“records”**的集合,它包含类似于以下示例文档的文档:
{
"_id": ObjectId("570c04a4ad233577f97dc459"),
"score": 1034,
"location": { state: "NY", city: "New York" }
}
“location”字段是一个内嵌文档,包含嵌入式字段city和state。下面的命令创建一个索引的**"location"**字段作为一个整体:
db.records.createIndex( { location: 1 } )
以下查询可以使用**"location"**字段的索引:
db.records.find( { location: { city: "New York", state: "NY" } } )
一些驱动程序可能指定索引,使用NumberLong(1)而不是1作为规范。这对结果索引没有任何影响。
译者:杨帅 莫薇
最近更新 1yr ago