node.js - 如何使用聚合对 mongodb 进行分组
问题描述
我正在尝试用他的才能和人才媒体填充我的用户文档。但我得到了重复的对象。我想将人才作为一个对象,并让媒体在一个阵列中反对该人才。
我的用户模型:
{
_id: '5f1acd6e6985114f2c1567ea',
name: 'test user',
email: 'test@email.com'
}
人才模型
{
_id: '5f1acd6e6985114f2c1567fa',
categoryId: '5f1acd6e6985114f2c1567ga',
userId: '5f1acd6e6985114f2c1567ea'
level: '5',
}
人才媒体模式
{
_id: 5f1acd6e6985114f2c156710',
talentId: '5f1acd6e6985114f2c1567fa',
media: 'file.jpg',
fileType: 'image'
}
我有另一个存储类别的模型
{
_id: '5f1acd6e6985114f2c1567ga',
title: 'java'
}
我想要的结果如下
user: {
_id: '',
name: 'test user',
email: 'test@email.com',
talents: [
{
_id: '',
level: '5',
categoryId: {
_id: '',
title: 'java'
},
medias: [
{
_id: '',
file: 'file1.jpg',
fileType: 'image'
},
{
_id: '',
file: 'file2.jpg',
fileType: 'image'
},
]
}
]
}
我还尝试在人才文件中添加嵌入人才媒体。但在 MongoDB 文档中找到的大部分不推荐使用。有这样的人才模型是不是更好,
{
_id: '5f1acd6e6985114f2c1567fa',
categoryId: '5f1acd6e6985114f2c1567ga',
userId: '5f1acd6e6985114f2c1567ea'
level: '5',
medias: [
{
_id: '',
file: 'file1.jpg',
fileType: 'image'
},
{
_id: '',
file: 'file2.jpg',
fileType: 'image'
},
]
}
解决方案
您可以通过多次使用$lookup来实现:
db.users.aggregate([
{
$lookup: {
from: "talents",
let: {
userId: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$$userId",
"$userId"
]
}
}
},
{
$lookup: {
from: "categories",
let: {
categoryId: "$categoryId"
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$$categoryId",
"$_id"
]
}
}
},
{
$project: {
_id: "",
title: 1
}
}
],
as: "categoryId"
}
},
{
$lookup: {
from: "talent_media",
let: {
talentId: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$$talentId",
"$talentId"
]
}
}
},
{
$project: {
_id: "",
file: "$media",
fileType: "$fileType"
}
}
],
as: "medias"
}
},
{
$unwind: {
path: "$categoryId",
preserveNullAndEmptyArrays: true
}
},
{
$project: {
_id: "",
categoryId: 1,
level: 1,
medias: 1
}
}
],
as: "talents"
}
},
{
$project: {
_id: "",
email: 1,
name: 1,
talents: 1
}
}
])
*您可能必须调整集合名称。
推荐阅读
- mysql - 将更改日志表加入事件表(SparkSQL)
- node.js - Node js登录使用passport-local在邮递员中工作,但在前端Vue JS中出错
- javascript - 在 js 中的 azure blob 上设置元数据
- python - 添加到 ADDON_MANAGERS 时,插件不会出现在菜单上
- r - ggfittext 可以自动为文本选择旋转吗?
- apache-nifi - 处理来自 GetS/List SFTP 处理器的最新文件
- angular - 如何让 Angular 使用 HTTP 而不是 HTTPS?
- node.js - 没有明确指定数据库的 TypeORM 连接
- html - 如何在引导程序中将同一行中的 svg 图标和文本内容对齐到右侧(右对齐)
- python - 使用生成的数据流式传输 S3 上传