我需要为三个不同的字段获取三个不同的值列表,但我想避免多次查询数据库。我确定答案是使用 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');
最佳答案
您可以 $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" ] }
}
}
}
}
])
关于mongodb - Mongoose:为多个数组字段获取多个不同的值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63843129/