【问题标题】:Many to many relationship using spring boot and mongoDB使用spring boot和mongoDB的多对多关系
【发布时间】:2021-06-05 06:03:27
【问题描述】:

我是 Spring Boot 技术的新手。

我有一个问题,当传递另一个集合的objectId 并检索该对象的详细信息时,如何使用 Spring Boot 映射多对多关系。

例如: 有两个模型名为 VehiclesCategories。在创建新的车辆类型时,我们可以传递Category Id,如下所示。

检索Vehicle 时应显示如下。

本示例使用 node.js 和 express.js 开发。

像这样我可以为弹簧靴做到这一点。我尝试了@JoinColumns@DBRef,但它们都不适合我。

这是我的模型。

车辆模型

    @Document(collection = "Vehicle")
    public class Vehicle {
    @Id
    private String id;
    private String name;
    private String type;
    private List<Category> categoryList;

   //getters and setters go here

类别模型

@Document(collection = "Category")
public class Category {
    @Id
    private String id;
    private String name;
    private Double amount;

//getters and setters go here

如果你能告诉我按照这个实现Controller和Service或Repository的方式就更好了。

提前致谢。

【问题讨论】:

    标签: mongodb spring-boot many-to-many


    【解决方案1】:

    在 spring-boot 方面无法为您提供帮助,但您需要执行 $lookup 操作以使用您正在使用的 mongodb 驱动程序加入外部文档。

    以下是使用 mongo shell 的方法:

    db.Vehicle.aggregate(
        [
            { $match: { _id: "vehicle-id" } },
            {
                $lookup: {
                    from: "Category",
                    localField: "categories._id",
                    foreignField: "_id",
                    as: "categories"
                }
            }
        ])
    

    在此处查看实际操作:https://mongoplayground.net/p/OgXrAxE2uXu

    ගුඩ් ලක්‌!

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多