1. Overview
In this tutorial, we’ll learn how to configure MongoDB collection names for our classes, along with a practical example. We’ll be using Spring Data, which gives us a few options to achieve this with little configuration. We’ll explore each option by building a simple music store. That way, we can find out when it makes sense to use them.
2. Use Case and Setup
Our use case has four simple classes: MusicAlbum, Compilation, MusicTrack, and Store. Each class will have its collection name configured in a different way. Also, each class will have its own MongoRepository. No custom queries will be needed. Moreover, we’ll need a properly configured instance of a MongoDB database.
2.1. Service to List Contents of a Collection by Name
Firstly, let’s write a controller to assert our configurations are working. We’ll do that by searching by collection name. Note that when using repositories, collection name configurations are transparent:
@RestController
@RequestMapping("/collection")
public class CollectionController {
@Autowired
private MongoTemplate mongoDb;
@GetMapping("/{name}")
public List<DBObject> get(@PathVariable String name) {
return mongoDb.findAll(DBObject.class, name);
}
}
This controller is based around MongoTemplate and uses the generic type DBObject, which doesn’t depend on classes and repositories. Also, this way, we’ll be able to see internal MongoDB properties. Most importantly, the “_class” property, used by Spring Data to unmarshal a JSON object, guarantees our configuration is correct.
2.2. API Service
Secondly, we’ll start building our service, which just saves objects and retrieves their collection. The Compilation class will be created later on in our first configuration example:
@Service
public class MusicStoreService {
@Autowired
private CompilationRepository compilationRepository;
public Compilation add(Compilation item) {
return compilationRepository.save(item);
}
public List<Compilation> getCompilationList() {
return compilationRepository.findAll();
}
// other service methods
}
2.3. API Endpoints
Finally, let’s write a controller to interface with our application. We’ll expose endpoints for our service methods:
@RestController
@RequestMapping("/music")
public class MusicStoreController {
@Autowired
private MusicStoreService service;
@PostMapping("/compilation")
public Compilation post(@RequestBody Compilation item) {
return service.add(item);
}
@GetMapping("/compilation")
public List<Compilation> getCompilationList() {
return service.getCompilationList();
}
// other endpoint methods
}
After that, we’re ready to start configuring our classes.
3. Configuration With @Document Annotation
Available since Spring Data version 1.9, the Document annotation does everything we’ll need. It’s specific for MongoDB but similar to JPA’s Entity annotation. As of this writing, there’s no way to define a naming strategy for collection names, only for field names. Therefore, let’s explore what’s available.
3.1. Default Behavior
The default behavior considers the collection name to be the same as the class name but starting with lower case. In short, we just need to add the Document annotation, and it’ll work:
@Document
public class Compilation {
@Id
private String id;
// getters and setters
}
After that, all inserts from our Compilation repository will go into a collection named “compilation” in MongoDB:
$ curl -X POST http://localhost:8080/music/compilation -H 'Content-Type: application/json' -d '{
"name": "Spring Hits"
}'
{ "id": "6272e26e04a673360d926ca1" }
Let’s list the contents of our “compilation” collection to verify our configuration:
$ curl http://localhost:8080/collection/compilation
[
{
"name": "Spring Hits",
"_class": "com.baeldung.boot.collection.name.data.Compilation"
}
]
And that’s the cleanest way to configure a collection name, as it’s basically the same as our class name. One disadvantage is that if we decide to change our database naming conventions, we’ll need to refactor all our classes. For instance, if we decide to use snake-case for our collection names, we won’t be able to take advantage of the default behavior.
3.2. Overriding the value Property
The Document annotation lets us override the default behavior with the collection property. Since this property is an alias for the value property, we can set it implicitly:
@Document("albums")
public class MusicAlbum {
@Id
private String id;
private String name;
private String artist;
// getters and setters
}
Now, instead of documents going into a collection named “musicAlbum”, they’ll go to the “albums” collection. This is the simplest way to configure a collection name with Spring Data. To see it in action, let’s add an album to our collection:
$ curl -X POST 'http://localhost:8080/music/album' -H 'Content-Type: application/json' -d '{
"name": "Album 1",
"artist": "Artist A"
}'
{ "id": "62740de003d2452a61a75c35" }
And then, we can fetch our “albums” collection, making sure our configuration works:
$ curl 'http://localhost:8080/collection/albums'
[
{
"name": "Album 1",
"artist": "Artist A",
"_class": "com.baeldung.boot.collection.name.data.MusicAlbum"
}
]
Also, it’s great for adapting our application to an existing database, with collection names that don’t match our classes. One downside is that if we needed to add a default prefix, we’d need to do it for every class.
3.3. Using a Configuration Property With SpEL
This combination can help do things that are not possible using the Document annotation alone. We’ll start with an application-specific property that we want to reuse among our classes.
First, let’s add a property to our application.properties that we’ll use as a suffix to our collection names:
collection.suffix=db
Now, let’s reference it with SpEL via the environment bean to create our next class:
@Document("store-#{@environment.getProperty('collection.suffix')}")
public class Store {
@Id
private String id;
private String name;
// getters and setters
}
Then, let’s create our first store:
$ curl -X POST 'http://localhost:8080/music/store' -H 'Content-Type: application/json' -d '{
"name": "Store A"
}'
{ "id": "62744c6267d3a034ec5e5719" }
As a result, our class will be stored in a collection named “store-db”. Again, we can verify our configuration by listing its contents:
$ curl 'http://localhost:8080/collection/store-db'
[
{
"name": "Store A",
"_class": "com.baeldung.boot.collection.name.data.Store"
}
]
That way, if we change our suffix, we don’t have to manually change it in every class. Instead, we just update our properties file. The downside is that it’s more boilerplate, and we still have to write the class name anyway. However, it can also help with multitenancy support. For example, instead of a suffix, we could have the tenant ID to mark collections that are not shared.
3.4. Using a Bean Method With SpEL
Another downside of using SpEL is that it requires extra work to evaluate programmatically. But, it opens up a lot of possibilities, like calling any bean method to determine our collection name. So, in our next example, we’ll create a bean to fix a collection name to conform with our naming rules.
In our naming strategy, we’ll use snake-case. First, let’s borrow code from Spring Data’s SnakeCaseFieldNamingStrategy to create our utility bean:
public class Naming {
public String fix(String name) {
List<String> parts = ParsingUtils.splitCamelCaseToLower(name);
List<String> result = new ArrayList<>();
for (String part : parts) {
if (StringUtils.hasText(part)) {
result.add(part);
}
}
return StringUtils.collectionToDelimitedString(result, "_");
}
}
Next, let’s add that bean to our application:
@SpringBootApplication
public class SpringBootCollectionNameApplication {
// main method
@Bean
public Naming naming() {
return new Naming();
}
}
After that, we’ll be able to reference our bean via SpEL:
@Document("#{@naming.fix('MusicTrack')}")
public class MusicTrack {
@Id
private String id;
private String name;
private String artist;
// getters and setters
}
Let’s try it by adding an item to our collection:
$ curl -X POST 'http://localhost:8080/music/track' -H 'Content-Type: application/json' -d '{
"name": "Track 1",
"artist":"Artist A"
}'
{ "id": "62755987ae94c5278b9530cc" }
Consequently, our track will be stored in a collection named “music_track”:
$ curl 'http://localhost:8080/collection/music_track'
[
{
"name": "Track 1",
"artist": "Artist A",
"_class": "com.baeldung.boot.collection.name.data.MusicTrack"
}
]
Unfortunately, there’s no way to obtain the class name dynamically, which is a major downside, but it allows for changing our database naming rules without having to manually rename all our classes.
4. Conclusion
In this article, we explored the ways we can configure our collection names using the tools Spring Data provides us. Further, we saw the advantages and disadvantages of each, so we can decide what works best for a specific scenario. During that, we built a simple use case to showcase the different approaches.
And as always, the source code is available over on GitHub.