Skip to content

Instantly share code, notes, and snippets.

@Prinzhorn
Last active December 16, 2015 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Prinzhorn/5403331 to your computer and use it in GitHub Desktop.
Save Prinzhorn/5403331 to your computer and use it in GitHub Desktop.
MongoDB unique+sparse bug?

From http://docs.mongodb.org/manual/core/indexes/#sparse-indexes

Any document that is missing the field is not indexed.

--

You can combine the sparse index option with the unique indexes option so that mongod will reject documents that have duplicate values for a field, but that ignore documents that do not have the key.

> db.users.ensureIndex({ a: 1, b: 1 }, { sparse: true, unique: true });
> db.users.insert({a: 'a', b: 'b'});
> db.users.insert({a: 'a', b: 'b'});
E11000 duplicate key error index: uq.users.$a_1_b_1 dup key: { : "a", : "b" }
//As expected
> db.users.insert({a: 'a'});
> db.users.insert({a: 'a'});
E11000 duplicate key error index: uq.users.$a_1_b_1 dup key: { : "a", : null }
//DAFUG. It's sparse. Y U SET NULL?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment