2

I'm using Mongodb as persistent layer with Spring Boot. In my project I want to achieve multi-tenant feature with creating a collection for each tenant. E.g. if there are three tenant, I will have 3 user collections: tenant1_user, tenant2_user, tenant3_user. So I write the model class as following:

@Document(collection = "#{tenantResolver.getCurrentTenant()}_user")
public class User {
    private String name;
    ...
}

tenantResolver.getCurrentTenant() gives the current tenant. If there's no tenant provided, the default tenant is NOT_PROVIDED.

This worked well until I tried to introduce index into my Mongodb. I tried 2 ways to make the field "name" an index:

a. Add @Indexed annotation in front of the "name" field.

@Document(collection = "#{tenantResolver.getCurrentTenant()}_user")
public class User {
    @Indexed
    private String name;
    ...
}

b. Use @CompoundIndexes.

@CompoundIndexes({
    @CompoundIndex(name = "name_1", def = "{'name': 1}")
})
@Document(collection = "#{tenantResolver.getCurrentTenant()}_user")
public class User {
    private String name;
    ...
}

And the behavior of them are very strange:

  1. Just after the service starts up (NO request comes yet), a collection named "NOT_PROVIDED_user" is created, and there is a "name_1" index created. Since there haven't been any request, so the tenant is the default tenant "NOT_PROVIDED". But my question is why is this collection created before any request comes?

  2. Then I use "tenant1" to send a request to the service, a new collection named "tenant1_user" is created as I expected. But the problem is the index "name_1" is not created. There's only one index "id".

Can anyone tell me the reason and guide me how to create index in my multi-tenant case? Thank you!

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
Cong Wang
  • 769
  • 1
  • 9
  • 30

0 Answers0