Info
Applying a unique index to a single text field has unexpected behavior with spaces.
OS: Windows 10
For example:
Inserting "test co" and "test2 co" fail uniqueness.
Inserting " co" and "
co" fail uniqueness.
Top User Comments
matherz831 commented on Mon, 21 May 2018 19:03:04 +0000:
Thanks for the help Andy. You are right, this is not a bug, but user error. I should be just be indexing strings.
As far as it possibly being a bug that mongodb allows the creation of a unique text index, I do see it possibly being useful when used with weights.
You may close/delete the issue.
schwerin commented on Fri, 18 May 2018 00:31:31 +0000:
It may be a bug that we allow you to create a unique text index. A text index splits strings into tokens (words), and those tokens form the keys. So in your example, "co" is a duplicates key.
Are you trying to build a text index, or just index strings? If the latter, you need to change your index spec.
Steps to Reproduce
Used the mongo shell on powershell.
> use test
switched to db test
> db.testCol.createIndex( { "name": "text" } , { unique: true } );
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.testCol.insert( {"name": "test co"} )
WriteResult( { "nInserted" : 1 })
> db.testCol.insert( {"name": "test2 co"})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.testCol index: name_text dup key: { : \"co\", : 0.75 }"
}
})