mongodb - 如何聚合集合中的嵌套字段?
问题描述
我正在创建一个论坛,结构是:
forum -> threads -> thread has a user
我想聚合它而不是填充,我当前的代码是:
const forums = await Forum.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId(req.params.id),
},
},
{
$lookup: {
from: "threads",
localField: "_id",
foreignField: "forumId",
as: "threads",
},
},
{
$lookup: {
from: "users",
localField: "threads.user",
foreignField: "_id",
as: "threads.user",
},
},
]);
但返回的线程对象有一个用户数组,它会覆盖所有其他线程值。我还希望用户成为一个对象,而不是只有一个用户的数组。我怎么做?
解决方案
感谢@turivishal,我想通了
代码是:
const forums = await Forum.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId(req.params.id),
},
},
{
$lookup: {
from: "threads",
localField: "_id",
foreignField: "forumId",
as: "threads",
},
},
{
$unwind: "$threads",
},
{
$lookup: {
from: "users",
localField: "threads.user",
foreignField: "_id",
as: "threads.user",
},
},
{
$unwind: "$threads.user",
},
{
$group: {
_id: "$_id",
name: { $first: "$name" },
threads: { $push: "$threads" },
},
},
]);
推荐阅读
- node.js - 如何从验证功能访问注册功能元素?
- docker - docker-ce 无法映射端口 - 表示端口正在使用中(即使没有使用)
- javascript - 使用 javascript 调整 3 张图像的大小
- java - 如何正确地将 java 集合转换为 Kotlin 语言
- python - 有没有办法使用索引和列名作为键从熊猫数据框中创建键值配对字典?
- python - Python 无法安装加密:命令错误,退出状态为 1
- apache-kafka - 消息没有被消费
- r - 计算 POSIXct 值之间的时间差
- python - 如何将两个 3D 数据与 python 进行比较?
- java - 春季卡夫卡:UnknownHostException:34bcfcc207e0