我使用java代码
创建了mongo db集合索引dbCollection.createIndex("accountNumber");
当我看到使用
的指数时db.accounts.getIndexes()
我将索引名称设为“accountNumber_1”
如何获取索引名称也与文档字段相同?或者如何给出索引名称?
命名索引是重要的还是我可以忽略它?
答案 0 :(得分: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
是符合name
结构的BSON
的值。我们可以忽略它......
答案 1 :(得分:0)
您可以使用createIndex方法的另一个变体创建所需名称的索引,请参阅java API here。
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.
Parameters: keys - a document that contains pairs with the name of the field or fields to index and order of the index options - a document that controls the creation of the index. MongoDB documentation Index Creation Tutorials
您可以使用相应的mongodb文档here。
基本上是第二个参数'选项'包含一个显式提供索引名称的选项。