我使用 Java 代码创建了 Mongo DB 集合索引。
dbCollection.createIndex("accountNumber");
当我看到使用索引时,
db.accounts.getIndexes()
我得到的索引名称为"accountNumber_1"
如何获得与文档字段相同的索引名称?或者如何指定索引名称?
索引命名是否重要?我可以忽略它吗?
我使用 Java 代码创建了 Mongo DB 集合索引。
dbCollection.createIndex("accountNumber");
db.accounts.getIndexes()
我得到的索引名称为"accountNumber_1"
如何获得与文档字段相同的索引名称?或者如何指定索引名称?
索引命名是否重要?我可以忽略它吗?
当我们在文档users
上创建索引时
> db.users.createIndex({name: 1})
{
"ok" : 0,
"errmsg" : "Index with name: name_1 already exists with different option
s",
"code" : 85
}
当返回name: name_1
时,我们可以通过getIndexes()
获取索引。
> db.users.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.users"
},
{
"v" : 1,
"unique" : true,
"key" : {
"name" : 1
},
"name" : "name_1",
"ns" : "test.users",
"background" : true,
"safe" : null
}
]
name_1
只是索引 name
的值。而键 name
用于为文档 users
创建索引。我认为 name_1
是 BSON
结构中的 name
值。我们可以忽略它...你可以使用createIndex方法的其他变体来创建你想要的索引,参考Java API 这里。
public void createIndex(DBObject keys,
DBObject options)
Creates an index on the field specified, if that index does not already exist.
Prior to MongoDB 3.0 the dropDups option could be used with unique indexes allowing documents with duplicate values to be dropped when building the index. Later versions of MongoDB will silently ignore this setting.
参数:
keys - 包含要索引和排序的字段名称或字段对的文档
options - 控制索引创建的文档。
MongoDB 文档
索引创建教程
hint
指定mongo要使用哪个索引时,你需要指定被索引的字段名,而不是实际的索引名称:db.users.find().hint( { age: 1 } )
- Lix