MongoDB Aggregate $lookup on array of object with additional field(MongoDB在具有附加字段的对象数组上聚合$lookup)
问题描述
我有两个不同的集合(下面的示例)方法 &项目.至于现在,我正在为 $lookup 使用 pre 3.6 vanilla 聚合查询:
I have two different collections (example below) methods & items. As for now, I'm using pre 3.6 vanilla aggregation query for $lookup:
MongoPlayground 示例
{
$lookup: {
from: "items",
localField: "reagents._id",
foreignField: "_id",
as: "reagent_items"
}
}
问题是,如果我使用它,我会在 $lookup 阶段错过 quantity 字段(来自嵌入的 methods.reagents)原创收藏.现在,我在 lookup 之后立即返回 quantity 但正如我听说的那样,Mongo 从 3.6 引入了一种用于 lookup 查询的新语法,所以问题是:
The problem is that if I am using it, I miss quantity field (from methods.reagents embedded) during $lookup stage from original collection. For now, I return quantity right after lookup but as I heard, Mongo introduced from 3.6 a new syntax for lookup queries, so the question is:
它能否解决我收到以下结果的问题:
Can it solve my problem for receiving the following results:
{
"_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"
}
推荐答案
使用 $map 以及 $arrayElemAt 为每个 reagent_items 找到对应的 reagent 并应用 $mergeObjects 获取一个对象:
Use $map along with $arrayElemAt to find corresponding reagent for each reagent_items and the apply $mergeObjects to get one object:
db.methods.aggregate([
{
$lookup: {
from: "items",
localField: "reagents._id",
foreignField: "_id",
as: "reagent_items"
}
},
{
$project: {
_id:1,
name: 1,
reagents: 1,
reagent_items: {
$map: {
input: "$reagent_items",
as: "ri",
in: {
$mergeObjects: [
"$$ri",
{
$arrayElemAt: [ { $filter: { input: "$reagents", cond: { $eq: [ "$$this._id", "$$ri._id" ] } } }, 0 ]
}
]
}
}
}
}
}
])
Mongo 游乐场
这篇关于MongoDB在具有附加字段的对象数组上聚合$lookup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MongoDB在具有附加字段的对象数组上聚合$lookup
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
