8

I am using the MongoDB C# driver to create an index

When my app starts up, it creates the index as below

await collection.Indexes.CreateOneAsync(new BsonDocument("code", 1), new CreateIndexOptions() { Unique = true, Sparse = true });

My question is this: If the index already exists, the index will not be re-created/indexed again, correct?

1
  • 1
    Should not create a new one as long as everything is the same... however it'd have been REALLY easy to just try it, create the index several times then list them? Commented Sep 1, 2015 at 6:28

1 Answer 1

8

Yes.

As long as the parameters don't change (e.g "code" becomes "Code" or Sparse becomes false) the index will not be recreated and the operation will be a no-op.

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

3 Comments

so when is the best time for index creation when one is creating web api using DI containers and repository pattern? Maybe in constructors of repositories? But as repositories has lifetime of http requests it couse CreateIndex command to be send for every incoming request. Sure it would be no-op in 99% cases but still - isn't it a overkill?
@lukpep where is that web api is hosted. There's usually something alive throughout the service lifetime. Just call createIndex when the server starts once. The next time you start the server it will be a no-op.
I'm using ms azure. I was thinking to do it in initial configuration of my mongo module (where conventions are registered etc.) but I don't like idea that every time I crate new domain repository I have to remember to go to mongo configuration module and add indexes. I would be really convenient to register needed indexes in repository somehow. Maybe autofac could get all classes from assembly that implement some marker interface IMongoRepository and look for static array of idexes to register on initial startup?

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.