指定文本索引的名称

    在本页面

    在MONGODB 4.2中的改变

    从4.2版本开始,由于特性兼容性版本设置为“4.2”或更大,MongoDB删除了最大127字节的索引名长度限制。在以前的版本或特性兼容性版本(fCV)设置为“4.0”的MongoDB版本中,索引名必须在这个限制之内。

    索引的默认名称由与串联的每个索引字段名称组成_text。例如,下面的命令创建一个text上的字段索引contentusers.commentsusers.profiles

    索引的默认名称由每个索引字段名和_text连接起来组成。例如,下面的命令在字段contentusers.commentsusers.profiles上创建一个文本索引:

    1. db.collection.createIndex(
    2. {
    3. content: "text",
    4. "users.comments": "text",
    5. "users.profiles": "text"
    6. }
    7. )

    索引的默认名称是:

    1. "content_text_users.comments_text_users.profiles_text"

    指定text索引名称

    您可以将name选项传递给 db.collection.createIndex()方法:

    1. db.collection.createIndex(
    2. {
    3. content: "text",
    4. "users.comments": "text",
    5. "users.profiles": "text"
    6. },
    7. {
    8. name: "MyTextIndex"
    9. }
    10. )

    使用索引名称删除text索引

    无论是文本索引具有默认名称或指定一个名称为文本索引,删除该文本索引,通过索引名称的db.collection.dropIndex()方法。

    例如,考虑以下操作创建的索引:

    1. db.collection.createIndex(
    2. {
    3. content: "text",
    4. "users.comments": "text",
    5. "users.profiles": "text"
    6. },
    7. {
    8. name: "MyTextIndex"
    9. }
    10. )

    然后,要删除此文本索引,请将名称传递"MyTextIndex"db.collection.dropIndex()方法,如下所示:

    1. db.collection.dropIndex("MyTextIndex")

    若要获取索引的名称,请使用 db.collection.getIndexes()方法。

    译者:杨帅