0

The situation: I have mongo db collection with user info. Among other fields it contains some user_email and user_login. These fields should be unique. During registration i want to check the uniqueness. I'm doing it by

db.users.find( { $or: [ { user_email: email }, { user_name: name } ] } )

If i will find something, I can assume that data is not unique.

So the problem here is that users table can be huge and i decided to create compound index, based on these two fields. Mongo docs says:

When using indexes with $or queries, each clause of an $or can use its own index. Consider the following query:

db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )

To support this query, rather than a compound index, you would create one index on quantity and another index on price:

db.inventory.createIndex( { quantity: 1 } )

db.inventory.createIndex( { price: 1 } )

MongoDB can use all but the geoHaystack index to support $or clauses.

So now I have 3 options:

  • compound index

  • two indexes

  • geoHaysatck index ( read about it a bit, seems that it can search for "closest" index entry. Not sure this is the way that I should use )

Could you guys give me some hints on index picking for this particular use case?

1
  • 1
    If you don't know what it is then you simply do not use it. I think the documentation is pretty clear on what works best, don't you? I mean you actually included the very part that confirms what to do in your question. Commented Jun 13, 2017 at 13:16

1 Answer 1

2

You should use two separate indexes. If you create a compound index, it will be useful for at most one of the two $or options.

With your $or query, the two parts will act much like separate queries:

  1. db.users.find( { user_email: email } )
  2. db.users.find( { user_name: name } )

If you create a compound index, say on user_email then user_name, then the first query will be able to make effective use of this - but the second query will not. The only way to optimise both parts of the query is to have separate indexes, one on each field.

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.