14

I am working with Spring MongoDb.

I create various entities using 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 of the inserted document.

What is the best way to get it?

Madhur Ahuja
  • 22,211
  • 14
  • 71
  • 124
  • 1
    `If your object has an "Id' property, it will be set with the generated Id from MongoDB`, have an attribute called `Id`. Once this method is called, the Object you passed will have its `Id` attribute filled. – BatScream Nov 18 '14 at 03:42
  • Moreover you need not return anything, since the object would be mutable. – BatScream Nov 18 '14 at 03:54
  • Thanks. I would need to return it in the response of my REST API. I have an API exposed to create a document – Madhur Ahuja Nov 18 '14 at 03:59
  • 4
    Okay, you can always do `insert(someObject);` `return someObject.getId()`. – BatScream Nov 18 '14 at 04:01
  • To return id you need to expose them. https://stackoverflow.com/questions/32480782/id-missing-in-the-json-response-with-spring-data-in-mongodb – Ajay Menon Oct 12 '21 at 18:56

2 Answers2

31

This is pretty interesting and thought I would share. I just figured out the solution for this with the help of BatScream comment above:

You would create an object and insert it into your MongoDB:

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

    mongoTemplate.insert(animal);

Your animal class looks like this with 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 done the insert under mongoTemplate.insert(animal);, you can actually call the method animal.getId() and it will return back the ObjectId that was created.

Set
  • 47,577
  • 22
  • 132
  • 150
Simon
  • 19,658
  • 27
  • 149
  • 217
2

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

if this is the case: use animal = template.insert(animal).

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Philip
  • 165
  • 1
  • 12