Reputation: 387
I'm trying to optimize my MongoDB collections. This is the example:
@Document
class Article {
@Id
private String id;
@DBRef(lazy = true)
@CascadeSave
private List<Comment> comments;
private String title;
private String text;
// constructors, getters and setters are ommited
}
@Document
class Comment {
@Id
private String id;
private String text;
private String author;
// constructors, getters and setters are ommited
}
Look's quite simple. Get the article, then get all the comments for this article. But what if I already have article id, and just want to get all the comments for my article? Sure it's simple too. Every comment should have reference to the article it belongs to (for example article_id).
My question is how can I do it automatically? How can I insert article_id to the comment while saving/updating etc? Or I should add field to Comment class and than first save article, then get article_id, then get comments, add article_id, save comments and add comments to the article comments collection? This has no sense for me.
I'm using Java 10, with Spring Boot 2.0.5 including spring-data-mongodb and the reactive driver. I have also implemented @CascadeSave annotation for saving the comments while saving article.
Thanks for your replies.
Upvotes: 1
Views: 6438
Reputation: 1001
The schema you designed is relational based design. In Mongo, you should avoid referencing if possible as in your use case you can embed a list of comment to the article.
To save comment in the article you can use $push
function also available in spring-data-mongo
.
Upvotes: 4