【问题标题】:Mongoose: Get multiple distinct lists of values for multiple array fieldsMongoose:为多个数组字段获取多个不同的值列表
【发布时间】:2020-12-29 17:52:46
【问题描述】:

我需要为三个不同的字段获取三个不同的值列表,但我想避免多次查询数据库。我确定它使用 mongodb 聚合框架的答案,但是,我不确定如何使用它来选择不同的字符串列表?

tags: [{ type: String }],
categories: [{ type: String }],
hashtags: [{ type: String }],
...
let tags = await Model.distinct('tags');
let categories = await Model.distinct('categories');
let hashtags = await Model.distinct('hashtags');

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以通过常量值$group 从所有文档中获取数组数组,然后运行$reduce$setUnion 以获取唯一值:

    await Model.aggregate([
        {
            $group: {
                _id: null,
                tags: { $push: "$tags" },
                categories: { $push: "$categories" },
                hashtags: { $push: "$hashtags" }
            }
        },
        {
            $project: {
                tags: {
                    $reduce: {
                        input: "$tags",
                        initialValue: [],
                        in: { $setUnion: [ "$$value", "$$this" ] }
                    }
                },
                categories: {
                    $reduce: {
                        input: "$categories",
                        initialValue: [],
                        in: { $setUnion: [ "$$value", "$$this" ] }
                    }
                },
                hashtags: {
                    $reduce: {
                        input: "$hashtags",
                        initialValue: [],
                        in: { $setUnion: [ "$$value", "$$this" ] }
                    }
                }
            }
        }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      相关资源
      最近更新 更多