eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Introduction

In this tutorial, we’re going to learn how to define a unique field in MongoDB using Spring Data. Unique fields are an essential part of the DB design. They guarantee consistency and performance at the same time, preventing duplicate values where there shouldn’t be.

2. Configuration

Unlike relational databases, MongoDB does not offer the option to create constraints. Therefore, our only option is to create unique indexes. However, automatic index creation in Spring Data is turned off by default. Firstly, let’s go ahead and turn it on in our application.properties:

spring.data.mongodb.auto-index-creation=true

With that configuration, indexes will be created on boot time if they do not yet exist. But, we have to remember that we cannot create a unique index after we already have duplicate values. This would result in an exception being thrown during the startup of our application.

3. The @Indexed Annotation

The @Indexed annotation allows us to mark fields as having an index. And since we configured automatic index creation, we won’t have to create them ourselves. By default, an index is not unique. Therefore, we have to turn it on via the unique property. Let’s see it in action by creating our first example:

@Document
public class Company {
    @Id
    private String id;

    private String name;

    @Indexed(unique = true)
    private String email;

    // getters and setters
}

Notice we can still have our @Id annotation, which is completely independent of our index. And that’s all we need to have a document with a unique field. As a result, if we insert more than one document with the same email, it will result in a DuplicateKeyException:

@Test
public void givenUniqueIndex_whenInsertingDupe_thenExceptionIsThrown() {
    Company a = new Company();
    a.setName("Name");
    a.setEmail("[email protected]");

    companyRepo.insert(a);

    Company b = new Company();
    b.setName("Other");
    b.setEmail("[email protected]");
    assertThrows(DuplicateKeyException.class, () -> {
        companyRepo.insert(b);
    });
}

This approach is useful when we want to enforce uniqueness but still have a unique ID field generated automatically.

3.1. Annotating Multiple Fields

We can also add the annotation to multiple fields. Let’s go ahead and create our second example:

@Document
public class Asset {
    @Indexed(unique = true)
    private String name;

    @Indexed(unique = true)
    private Integer number;
}

Notice we’re not explicitly setting @Id on any field. MongoDB will still set an “_id” field for us automatically, but it won’t be accessible to our application. But, we cannot put the @Id along with a @Indexed annotation marked as unique on the same field. It would throw an exception when the application tried to create the index.

Also, now we have two unique fields. Note that this does not mean that it’s a compound index. Consequently, multiple inserts of the same value for any of the fields will result in a duplicate key. Let’s test it:

@Test
public void givenMultipleIndexes_whenAnyFieldDupe_thenExceptionIsThrown() {
    Asset a = new Asset();
    a.setName("Name");
    a.setNumber(1);

    assetRepo.insert(a);

    assertThrows(DuplicateKeyException.class, () -> {
        Asset b = new Asset();
        b.setName("Name");
        b.setNumber(2);

        assetRepo.insert(b);
    });

    assertThrows(DuplicateKeyException.class, () -> {
        Asset b = new Asset();
        b.setName("Other");
        b.setNumber(1);

        assetRepo.insert(b);
    });
}

If we want only the combined values to form a unique index, we have to create a compound index.

3.2. Using a Custom Type as an Index

Similarly, we can annotate a field of a custom type. That will achieve the effect of a compound index. Let’s start with a SaleId class to represent our compound index:

public class SaleId {
    private Long item;
    private String date;

    // getters and setters
}

Let’s now create our Sale class to make use of it:

@Document
public class Sale {
    @Indexed(unique = true)
    private SaleId saleId;

    private Double value;

    // getters and setters
}

Now, every time we try to add a new Sale with the same SaleId, we’ll get a duplicate key. Let’s test it:

@Test
public void givenCustomTypeIndex_whenInsertingDupe_thenExceptionIsThrown() {
    SaleId id = new SaleId();
    id.setDate("2022-06-15");
    id.setItem(1L);

    Sale a = new Sale(id);
    a.setValue(53.94);

    saleRepo.insert(a);

    assertThrows(DuplicateKeyException.class, () -> {
        Sale b = new Sale(id);
        b.setValue(100.00);

        saleRepo.insert(b);
    });
}

This approach has the advantage of keeping the index definition separate. This allows us to include or remove new fields from SaleId without having to recreate or update our index. It’s also very similar to a composite key. But, indexes differ from keys because they can have one null value.

4. The @CompoundIndex Annotation

To have a unique index comprised of multiple fields without a custom class, we have to create a compound index. For that, we use the @CompoundIndex annotation directly in our class. This annotation contains a def property that we’ll use to include the fields we need. Let’s create our Customer class defining a unique index for the storeId and number fields:

@Document
@CompoundIndex(def = "{'storeId': 1, 'number': 1}", unique = true)
public class Customer {
    @Id
    private String id;

    private Long storeId;
    private Long number;
    private String name;

    // getters and setters
}

This differs from @Indexed on multiple fields. This approach only results in a DuplicateKeyException if we try inserting a customer with the same storeId and number values:

@Test
public void givenCompoundIndex_whenDupeInsert_thenExceptionIsThrown() {
    Customer customerA = new Customer("Name A");
    customerA.setNumber(1l);
    customerA.setStoreId(2l);

    Customer customerB = new Customer("Name B");
    customerB.setNumber(1l);
    customerB.setStoreId(2l);

    customerRepo.insert(customerA);

    assertThrows(DuplicateKeyException.class, () -> {
        customerRepo.insert(customerB);
    });
}

With this approach, we have the advantage of not having to create another class just for our index. Also, it’s possible to add the @Id annotation to a field from the compound index definition. However, different from @Indexed, it won’t result in an exception.

5. Conclusion

In this article, we learned how to define unique fields for our documents. Consequently, we learned that our only option is to use unique indexes. Also, using Spring Data, we can easily configure our application to automatically create our indexes. And, we saw the many ways to use the @Indexed and @CompoundIndex annotations.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)