【问题标题】:Mongoose get the size of the relations from one collection to anotherMongoose 获取从一个集合到另一个集合的关系大小
【发布时间】:2021-02-11 00:06:12
【问题描述】:

我有一个Categories 收藏。还有另一个Videos 集合。每个视频都属于一个类别。

我想列出所有类别以及该类别中的视频数量。 我正在使用聚合来加入两者,并在类别集合中获取所需的字段。从视频集合中,我只需要与集合对应的视频数量。

如何使用聚合来获取总视频关系的大小?

或者我有什么遗漏的吗?

提前致谢

编辑: 关系基本上是,在每个视频中都有对应于类别的category_id

【问题讨论】:

    标签: database mongodb mongoose


    【解决方案1】:

    我得到了答案, 您可以使用 aggregate 以及 lookupproject 来获得结果

    await this.categories
                .aggregate([
                    {
                        $match: filter,
                    },
                    {
                        $lookup: {
                            from: 'resources',
                            localField: '_id',
                            foreignField: '_category_id',
                            as: 'videos',
                        },
                    },
                    {
                        $project: {
                            name: '$name',
                            count: { $size: '$videos' },
                        },
                    },
                ])
    

    【讨论】:

      猜你喜欢
      • 2016-08-25
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多