Default options for dynamic MongoDB collections

74 Views Asked by At

I am aware that MongoDB will dynamically create a collection when you attempt to insert a document into a non-existent collection. My question is: How do I set up default options so that the collection has the options I want when it is dynamically created?

2

There are 2 best solutions below

0
On

I don't think you can do that. Your options are:

  1. Pre-create the collections if the pattern is dynamic yet predictable.
  2. List the existing collections before inserting and create the new collection yourself with the right options if it's not already present.
  3. Do not use dynamic collections but rather put the dynamic part as a property to individual documents in a shared collection.
0
On

I chose to write a wrapper around mongoc_database_get_collection(). There is a little bit of additional overhead for an extra round trip request to the mongo server to see if the collection already exists. If not, the wrapper creates it with the options I want and returns the new collection. If the collection already exists, the wrapper returns the existing collection.