Mongo DB 索引名称

3

我使用 Java 代码创建了 Mongo DB 集合索引。

dbCollection.createIndex("accountNumber");

当我看到使用索引时,

db.accounts.getIndexes()

我得到的索引名称为"accountNumber_1"

如何获得与文档字段相同的索引名称?或者如何指定索引名称?

索引命名是否重要?我可以忽略它吗?


你需要使用索引名称的特定原因吗?当你在查询中使用hint指定mongo要使用哪个索引时,你需要指定被索引的字段名,而不是实际的索引名称:db.users.find().hint( { age: 1 } ) - Lix
1
请忽略此内容,名称并不重要。 - Sammaye
2个回答

2

当我们在文档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_1BSON 结构中的 name 值。我们可以忽略它...

0

你可以使用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 文档 索引创建教程
你可以在这里找到相应的 MongoDB 文档 here
基本上,第二个参数 'options' 包含一个选项来显式地提供索引名称。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接