Spring mongodb gets id of inserted element after saving

I am working with Spring MongoDb.

I create various objects using the insert method: http://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html#insert-java.lang .Object-

However, all methods return void . I need to return the ObjectId inserted document.

What is the best way to get it?

+10
spring-mongo mongodb
source share
2 answers

It is quite interesting and thought that I would share. I just figured out a solution for this using the BatScream comment above:

You must create an object and paste it into your MongoDB:

  Animal animal = new Animal(); animal.setName(name); animal.setCat(cat); mongoTemplate.insert(animal); 

Your animal class will look using getters and settings for all fields:

 public class Animal { @Id @JsonProperty private String id; @JsonProperty private String name; @JsonProperty private String cat; public String getId() { return id; } } 

AFTER you have nested a tab in mongoTemplate.insert(animal); , you can actually call the animal.getId() method, and it will return the ObjectId that was created.

+26
source share

I had the same problem with @AlanH that animal.getId() is null . And then I just realized that my identifier field was set as the final field with the wither method. Therefore, of course, getId() is null, because the id field is immutable, and the wither method returns a new object with id.

if so: use animal = template.insert(animal) .

0
source share

All Articles