indexing - MongoDB: How to create sparse+unique indexes with optional keys? -


i have collection stats.daily stores multiple dimensional data, depending type requires other specific keys.
, it's required these keys (depending type) unique.

example, in case url key required because type "url":

{     "site": 1,     "type": "url",     "url": "http://google.com/"     "totals": {         "variable1": 12,  // incrementing values         "variable2": 32     } } 

another example:

{     "site": 1,     "type": "domain",     "domain": "google.com",     "totals": {...} } 

so create indexes:

db.coll.createindex({site: 1, type: 1, url: 1}, {unique: true, sparse: true}); db.coll.createindex({site: 1, type: 1, domain: 1}, {unique: true, sparse: true}); 

it doesn't works, returns exception: e11000 duplicate key error index. makes sense unique index, should work sparse part.

what's best solution accomplish need?

edit:
in cases, depending type, there may have more 1 related key:

{     "site": 1,     "type": "search",     "engine": "google",     "term": "programming",     "totals": {...} } 

and unique index include these 2 new keys.


Comments