Enigman
Enigman

Reputation: 640

Sparse Index in MongoDB not working?

I'm trying to understand sparse index in MongoDB. I understand that if I do this :

> db.check.ensureIndex({"id":1},{sparse:true, unique:true})

I can only insert documents where the id field is not a duplicate and is also not absent. Hence, I tried,

> db.check.insert({id:1})
> db.check.insert({id:1})

which, as I expected, gave :

E11000 duplicate key error index: test.check.$id_1  dup key: { : 1.0 }

However, inserting a document with a non-existant id field :

> db.check.insert({})

works! What is going wrong?

Upvotes: 2

Views: 1092

Answers (2)

Philipp
Philipp

Reputation: 69663

A sparse unique index means that a document doesn't need to have the indexed field(s), but when it has that field, it must be unique.

You can add any number of documents into the collection when the field is absent. Note that when you insert an empty document, the _id field will get an auto-generated ObjectID which is (as good as guaranteed) unique.

Upvotes: 3

Joachim Isaksson
Joachim Isaksson

Reputation: 180887

That's pretty much what sparse means. From the docs;

Sparse indexes only contain entries for documents that have the indexed field. [5] Any document that is missing the field is not indexed.

In other words, your missing id field makes the index not even consider that entry for a unique check.

Upvotes: 1

Related Questions