简体   繁体   中英

MongoDB multiple case-insensitive fields unique index, error message does not make sense

I have a collection created with below index. Only name is of type string and check should be done in case insensitive manner. Only allows 'A' or 'a'

db.collection('myCollection').createIndex(
          { "name": 1, "type": 1, "ref": 1 }, { unique: true, collation: { locale: 'en', strength: 1 }});
      })
    }

I have tested and it works but I don't understand the error message:

{
    "errorMessage": "E11000 duplicate key error collection: my.myCollection index: name_1_type_1_ref_1 dup key: { : \"O1XO\u0006\u000c)MN11\", : \")MB1O1FG1\", : null }"
}

What does the dup key part mean? Is this the correct way to do this?

What is your mongodb server version? I try mongodb 4.0 its work;

 //mongodb version 4.0

db.createCollection("TestIndex");

db.getCollection('TestIndex').createIndex(
{ "name": 1, "type": 1, "ref": 1 }, { unique: true, collation: { locale: 'en', strength: 2 }});

db.getCollection('TestIndex').insert({ "name" : "A",
    "type" : "B",
    "ref" : "C"});

db.getCollection('TestIndex').insert({ "name" : "A",
    "type" : "B",
    "ref" : "c"});
//E11000 duplicate key error collection: test_db.TestIndex index: name_1_type_1_ref_1 dup key: { : ")", : "+", : "-" }

db.getCollection('TestIndex').drop();

db.createCollection("TestIndex");
db.getCollection('TestIndex').createIndex(
{ "name": 1, "type": 1, "ref": 1 }, { unique: true, collation: { locale: 'en', strength: 3 }});

db.getCollection('TestIndex').insert({ "name" : "A",
    "type" : "B",
    "ref" : "C"});
    //Inserted 1 record(s) in 11ms
db.getCollection('TestIndex').insert({ "name" : "A",
    "type" : "B",
    "ref" : "c"});

@AlexBlex在评论中指出这是错误: https ://jira.mongodb.org/browse/SERVER-26050

Latest finding

I found that I will have same error message if my existing collection already has any document that is crashed with the creating index . Please confirm that you do not have invalid document before creating the compound index then.


I experienced the same problem, when I did not give the proper index name in options param. MongoDB does not allow us create with duplicate index key but it will make use the involved fields and corresponding value to create the index name (in this case, it is name_1_type_1_ref_1) . Hence we need to add the name suffix with '_en' or maybe other suffix to avoid the duplicate error like following.

db.collection('myCollection').createIndex(
      { "name": 1, "type": 1, "ref": 1 }, 
      { name: "name_1_type_1_ref_1_en", 
        unique: true, 
        collation: { locale: 'en', strength: 1 }
      }
);

then the compound index can be successfully created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM