Description
Using spring-boot-starter-data-mongodb:2.6.6
spring-boot-starter:2.6.6
mongodb-driver-sync:4.4.2
spring-data-mongodb: 3.3.3
Documentation https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.id-handling states that the @MongoId
annotation can be used to control the data that gets written to mongodb. I want to write the auto generated _id
field to the database as a string, but no matter the annotations I use it always get's written as an ObjectId
.
Here is the code:
@SpringBootApplication
@EnableMongoRepositories
public class Demo1Application implements CommandLineRunner {
@Autowired
UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
@Override
public void run(String... args) throws Exception {
userRepository.deleteAll();
userRepository.save(new User());
}
}
@Document
class User {
@MongoId
String id;
}
interface UserRepository extends MongoRepository<User, String> {
}
And this is the data produced in the database:
{ "_id": { "$oid": "625da3621aab8475434b3b66" }, "_class": "com.example.demo.User"}
Even if I try @MongoId(targetType = FieldType.STRING)
the _id
field type in the database is still ObjectId
. If I use spring's @Id
annotation, the _id
field gets written as an ObjectId
which is no different to what @MongoId
produces.
Is this a bug or am I misunderstanding the use of @MongoId
? Thanks