Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb auto create index for new collections

I have a Node.JS server with a Mondodb database. Multiple clients use this same database, and each client has his own collection. The collections are named by the id of the client.

Since every client uses a different name for his data, when a new client connects to the server, the first operation he does on the database will create a new collection for him.

I need all the collections to have a specific index. Is there a way to automatically create this index for every new collection?

like image 894
Asher Avatar asked Aug 13 '15 14:08

Asher


1 Answers

No, there is no such command.

But don't be afraid to call createIndex too often. The documentation guarantees that when an index with the same settings already exists, nothing will happen. So you can attach it to some common database operations executed by new users. It's no big deal when it gets called more than once.

To highlight this behavior, the method used to be called ensureIndex, but that name is deprecated.

By the way: Having a different collection for every client is a quite unusual architecture. It has some drawbacks, like the problem with indexes and other collection-level configuration you already discovered, but also others like being unable to do any queries which use data from more than one client. With the default storage engine, there is the advantage that clients can not lock each other with collection-wide locks, but when you use the WiredTiger engine, that advantage is obsolete because WiredTiger locks only on document level.

A more conventional approach is to have one collection for all users and have a field in each document which says which user owns the document and which is part of all indexes used by user-specific queries.

like image 72
Philipp Avatar answered Oct 06 '22 01:10

Philipp