1

Is possible to call ensureIndex across collections (even for collections which have not been created yet)?

For example, let's say I have 3 collections within the same database: "london", "newyork" and "tokyo". I have a field called "employee_username" which must be unique across all present and future collections. That is, if someone called "susan" is registered as the "employee_username" within "london", the same cannot exist within the "newyork" collection. Further, if in future, I need to create a new collection called "hongkong", the "susan" cannot be used within the "employee_username" within it.

Is this possible?

Thanks!


Yes, thank you for your reply.

However, the MongoDB says "Generally, having a large number of collections has no significant performance penalty, and results in very good performance." in [http://www.mongodb.org/display/DOCS/Using+a+Large+Number+of+Collections].

The above example given is just example. I am planning to build a social database with millions of records. So - according to the documentation - I should separate into many collections as possible, for performance reasons. Therefore, if I cannot create unique index which spans across collections, then I think I will create an "Email Addresses" collection which contains only and nothing but email addresses, uniquely indexed.

Does anyone have any comments? (My approach considers performance and optimization is #1 factor.)

Thanks!

1 Answer 1

3

MongoDB doesn't support unique indexes that span several collections, so a good approach here would be to use a single collection with a unique index on employee_username, with documents having this sort of structure:

users

{
    _id: ObjectId("47cc67093475061e3d95369d"),
    location: "newyork",
    employee_username: "susan"
},
{
    _id: ObjectId("4dc9acea045bbf04348f9691"),
    location: "london",
    employee_username: "john"
}

To create the index:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.