【发布时间】:2020-08-14 06:48:40
【问题描述】:
我有两个不同的集合(下面的示例)methods & items。至于现在,我正在使用 3.6 之前的香草聚合查询 $lookup:
{
$lookup: {
from: "items",
localField: "reagents._id",
foreignField: "_id",
as: "reagent_items"
}
}
问题是,如果我使用它,我会在原始集合的$lookup 阶段错过quantity 字段(来自methods.reagents 嵌入)。现在,我在lookup 之后立即返回quantity,但据我所知,Mongo 从 3.6 开始为lookup 查询引入了新语法,所以问题是:
它能否解决我收到以下结果的问题:
{
"_id": 1,
"name": "Test",
"reagent_items": [ // <= the exact schema of what I need after lookup
{
"_id": 1,
"name": "ItemOne",
"other": "field",
"quantity": 2 //quantity field from original {array of objects} after lookup
},
{
"_id": 2,
"name": "ItemTwo",
"other": "field",
"quantity": 4 //quantity field from original {array of objects} after lookup
}
],
"reagents": [ //original reagents field here just for example, we could remove it
{
"_id": 1,
"quantity": 2
},
{
"_id": 2,
"quantity": 4
}
]
}
方法
{
"_id": 1,
"name": "Test",
"reagents": [
{
_id: 1,
quantity: 2
},
{
_id: 2,
quantity: 4
}
]
}
项目
{
"_id": 1,
"name": "ItemOne",
"other": "field"
},
{
"_id": 2,
"name": "ItemTwo",
"other": "field"
}
【问题讨论】:
标签: javascript mongodb mongoose mongodb-query aggregation-framework