开发者

References vs embeds in MongoDB

I'm trying to figure out how to best use MongoDB for a very small and simple use case, but finding the docs somewhat confusing. My document should represent the fact that a user can have many e开发者_如何学Pythonmails. If I follow the documentation the most obvious and simple solution is to use embeds. The problem is when I want to validate the email address for uniqueness, which is AFAIK impossible with embeds (of course I can use map/reduce, but it seems a very poor choice).

I definitely feel like emails don't deserve their own collection, but apparently embedded object doesn't let me do the validation (and if it does, I really don't believe it's going to be efficient). How would you design the schema in this situation ?


You can define an index on the email sub-field with { unique: true } set. This will prevent multiple copies of the email address from being stored in the collection.

For example, let's say your documents look something like this:

db.users.findOne() => 
{ 
  "name" : "xxxx", 
  "emails" : [ 
     { address: "one@domain.com", validated: false },
     { address: "two@domain.com", validated: true }
  ]
}

You can define a unique index on the email.address field like this:

db.users.ensureIndex(['emails.address',1], {unique: true})

Now you will get an error if you try to insert the same email address twice. It will also help you optimize looking up users by their email address which is bound to be useful in your app at some point or another.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜