1

This question is very similar to Get ID of last inserted document in a mongoDB w/ Java driver with one difference: I'm using a typed / generic collection.

Example DTO:

public class ForumMessageDTO {
    @Expose
    @BsonId
    private ObjectId id;
    private Long forumId;
    @Expose
    private Long userId;
    @Expose
    private Date created;
    @Expose
    private String message;
    /* getters and setters are not shown here but they are implemented.... */
}

Example code for inserting a document:

public ForumMessageDTO addMessage(Long forumId, Long userId, String message) {
    ForumMessageDTO dto = new ForumMessageDTO(forumId, userId, new Date(), message);
    messages.insertOne(dto);
    return dto; /* dto.id is null here!!! But why? */
}   

The returned dto should have its id field filled in, because it was annotated with @BsonId and it has ObjectId type. In reality, it remains null and I don't see how I could access the ObjectId of the inserted document.

This version of collection.insertOne does not return anything, and apparently it does not change the id field of the dto.

Probably I could manually convert the DTO into a Document and use that version of collection.insertOne, and then get the object id and put it back into the DTO but this is very inefficient. Considering the fact that I'm going to use many collections with many different DTO classes, and I do not want to write manual conversions for all of them.

So how can I retrieve the object id of the document that was just inserted?

nagylzs
  • 3,954
  • 6
  • 39
  • 70

0 Answers0