How to find by UUID in MongoDB

48 views Asked by At

I have a spring boot project where I use MongoDb-reactive and webflux.

I have entites that have a UUID as an _id. I'm trying to write an endpoint that accepts an UUID and returns the matching object.

Since findById accepts Strings, I tried to use it with id.toString() but my repository doesn't seem to find anything. My guess is that MongoDB doesn't returns the UUID as a plain string, but I can't figure out how it is saved.

My working solution for now are custom methods in the repository, which accepts UUID as parameters but there has to be another way using stringsp

1

There are 1 answers

0
Devin Chandrapala On

Your id field should be a String, annotated with @Id. It shouldn't be a UUID type.

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document("users")
public class User {
    @Id
    private String id;
}

You should be able to use your Spring Data Repository of choice to call .findById.

import org.springframework.data.mongodb.repository.ReactiveMongoRepository;

public interface UserRepository extends ReactiveMongoRepository<User, String> {
}
@RestController
@RequiredArgsConstructor
@RequestMapping("/users")
public class UserController {
    private final UserRepository userRepository;


    @GetMapping("/{id}")
    public Mono<Employee> getUserById(@PathVariable String id) {
        return userRepository.findById(id);
    }
}