开发者

mongoDB: unique index on a repeated value

So i'm pretty new to mongoDb so i figure this could be a misunderstanding on general usage. so bear with me. I have a document schema I'm working with as such

  { 
    name: "bob", 
    email: "bob@gmail.com", 
    logins: [ 
      { u: 'a', p: 'b', public_id: '123' }, 
      { u: 'x', p: 'y', public_id: 'abc' }
    ] 
  }

My Problem is that i need to ensure that the public ids are unique within a document and collection, Furthermore there are some existing records being migrated from a mySQL DB that dont have records, and will therefore all be replaced 开发者_如何转开发by null values in mongo.

I figure its either an index

db.users.ensureIndex({logins.public_id: 1}, {unique: true});

which isn't working because of the missing keys and is throwing a E11000 duplicate key error index:

or this is a more fundamental schema problem in that I shouldn't be nesting objects in an array structure like that. In which case, what? a seperate collection for the user_logins??? which seems to go against the idea of an embedded document.


If you expect u and p to have always the same values on each insert (as in your example snippet), you might want to use the $addToSet operator on inserts to ensure the uniqueness of your public_id field. Otherwise I think it's quite difficult to make them unique across a whole collection not working with external maintenance or js functions.

If not, I would possibly store them in their own collection and use the public_id as _id field to ensure their cross-document uniqueness inside a collection. Maybe that would contradict the idea of embedded docs in a doc database, but according to different requirements I think that's negligible.


Furthermore there are some existing records being migrated from a mySQL DB that dont have records, and will therefore all be replaced by null values in mongo.

So you want to apply a unique index on a data set that's not truly unique. I think this is just a modeling problem.

If logins.public_id is null that's going to violate your uniqueness constraint, then just don't write it at all:

  { 
    logins: [ 
      { u: 'a', p: 'b' }, 
      { u: 'x', p: 'y' }
    ] 
  }


Thanks all. In the end I opted to seperate this into 2 collections, one for users and one for logins. users this looked a little like..

   userDocument = {
      ...
      logins: [
        DBRef('loginsCollection', loginDocument._id), 
        DBRef('loginsCollection', loginDocument2._id),       
      ]
    }

   loginDocument = {
       ...
       user: new DBRef('userCollection', userDocument ._id)
    }

Although not what i was originally after (a single collection) It is working niocely and by utilising the MongoId uniquness there is a constraint now built in at a database level and not implemented at the application level.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜