With mongo 4.4.3 I am creating a unique and sparse index into an array:
db.test.createIndex( { "array": 1 }, { unique: true, sparse: true } )
I fill it with some test data:
db.test.insert({})
db.test.insert({array:[]})
db.test.insert({array:[ "a" ]})
db.test.insert({array:[ "b" ]})
db.test.insert({array:[ "c", "d" ]})
Now I would expect the following:
db.test.insert({array:[ "a" ]}) #FAIL
db.test.insert({array:[ "b" ]}) #FAIL
db.test.insert({array:[ "c" ]}) #FAIL
db.test.insert({array:[ "d" ]}) #FAIL
db.test.insert({}) #SUCCESS
db.test.insert({array:[]}) #SUCCESS
Instead I am getting:
db.test.insert({array:[ "a" ]}) #FAIL
db.test.insert({array:[ "b" ]}) #FAIL
db.test.insert({array:[ "c" ]}) #FAIL
db.test.insert({array:[ "d" ]}) #FAIL
db.test.insert({}) #SUCCESS
db.test.insert({array:[]}) #FAIL
With the problem being:
"E11000 duplicate key error collection: db.test index: array_1 dup key: { array: undefined }"
An empty array seems to be treated as undefined - but why is sparse ignored for that?
Is there a way to get the behavior that I expected (without an impact on performance)?