【发布时间】:2022-01-21 16:26:44
【问题描述】:
我有以下模型,它有一个类别数组,由具有类别的对象组成:ObjectId 和选项:[ObjectId, ObjectId]。
const page = new Schema({
"categories":[
{
"category":{
"type":"Schema.Types.ObjectId",
"ref":"Category",
"_id":false,
"index":true
},
"options":[
{
"type":"Schema.Types.ObjectId",
"ref":"CategoryOptions",
"_id":false,
"index":true
}
],
"_id":false
}
]
})
我正在尝试使用 .aggregate 方法填充字段。但是,不知何故,我无法在不丢失整体结构的情况下让它工作。 我的输出最终应该是这样的:
[
{
"category":{
"_id":"ObjectId",
"name":"name of category"
},
"options":[
{
"_id":"ObjectId",
"name":"name of options"
},
{
"_id":"ObjectId",
"name":"name of options"
}
]
}
]
我当前的聚合如下所示:
{
$lookup: {
from: 'categories',
localField: 'categories.category',
foreignField: '_id',
as: 'categories',
pipeline: [
{
$lookup: {
from: 'categoryoptions',
localField: 'options',
foreignField: '_id',
as: 'options'
}
}
]
}
}
但这不起作用,因为它只填充类别并将结构展平为类别:[...results]
知道如何在不丢失给定结构的情况下简单地填充值吗?
更新的解决方案:
{
$unwind: {
path: '$categories'
}
}, {
$lookup: {
from: 'categories',
localField: 'categories.category',
foreignField: '_id',
as: 'categoryObjects.category'
}
}, {
$set: {
categoryObjects: {
category: {
$first: '$categoryObjects.category'
}
}
}
}, {
$lookup: {
from: 'categoryoptions',
localField: 'categories.options',
foreignField: '_id',
let: {
cid: '$categories.options'
},
pipeline: [
{
$match: {
$expr: {
$in: [
'$_id', '$$cid'
]
}
}
}
],
as: 'categoryObjects.options'
}
}, {
$group: {
_id: '$_id',
categories: {
$push: '$categoryObjects'
},
__v: {
$first: '$__v'
}
}
}
enter code here
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework