Populating Database problem crossing tables


If I have for example this collection with this fields:

History entity
    private String historyId;
    private String userId;
    private String foodId;
    private double totalCalories;

And this Food entity

    private String foodId;
    private String name;
    private String description;
    private String image;
    private double calories;

How I can connect in Json so HistoryId pull foodId?

Hello @Stefan_Jankovic, Welcome to the MongoDB Community forum!

You do a “join” operation using the $lookup aggregation stage. That is you write an aggregation query to get the result you need.

Spring Data MongoDB has MongoTemplate class with aggregate method where you can perform the lookup operation. Also, using MongoRepository interface with the @Aggregation annotation.


An example using MongoTemplate#aggregate: