javascript - MongoDB 查找并映射 2 个结果数组
问题描述
我在 MongoDB 聚合管道中查找后有 2 个数组字段。
第一个
[
{
"colorId": "60828a1b216b0972da695f2a",
"name": "Exellent",
"description": "Great work"
}
]
第二个
[
{
"_id": "60828a1b216b0972da695f2a",
"colorName": "Green",
"hexColorCodes": "#2D9D78",
"sequence": 1,
"isActivated": true,
"created_at": "2021-04-23T08:49:31.729Z",
"updated_at": "2021-04-23T08:49:31.729Z",
"__v": 0,
"isDefault": true
}
]
我想要的结果是
[
{
"colorId": "60828a1b216b0972da695f2a",
"name": "Exellent",
"description": "Great work",
"colorName": "Green",
"hexColorCodes": "#2D9D78"
}
]
然后我想映射colorName
到hexColorCodes
第一个数组。这是我的聚合管道
db.collection.aggregate([
{
$lookup: {
from: "color_tags",
localField: "colors.colorId",
foreignField: "_id",
as: "tempColors",
},
},
{
$addFields: {
stages3: {
$map: {
input: "$colors",
in: {
$mergeObjects: [
"$$this",
{
$arrayElemAt: [
"$tempColors",
{
$indexOfArray: [
"$tempColors._id",
"$$this.colors.colorId",
],
},
],
},
],
},
},
},
},
}
])
但结果不是我所期望的。它映射了不正确的 ID。请建议。
解决方案
$map
first
迭代数组的循环$filter
second
迭代数组循环并匹配colorId
并_id
返回匹配结果$arrayElemAt
获取第一个匹配元素$mergeObjects
将当前对象与second
数组的返回结果合并
{
$project: {
first: {
$map: {
input: "$first",
as: "f",
in: {
$mergeObjects: [
"$$f",
{
$arrayElemAt: [
{
$filter: {
input: "$second",
cond: { $eq: ["$$this._id", "$$f.colorId"] }
}
},
0
]
}
]
}
}
}
}
}
如果要生成特定字段$project
,请在最后添加一个阶段,
{
$project: {
"first.colorId": 1,
"first.name": 1,
"first.description": 1,
"first.colorName": 1,
"first.hexColorCodes": 1
}
}
推荐阅读
- reactjs - 是的架构验证,其中一个字段是必需的,具体取决于另一个字段的值
- javascript - 你好,我想要一个不同的随机数,但我总是得到相同的,一个想法?
- arduino - 在 Arduino 设备 (ESP8266) 的 Visual Studio Code 中看不到 Serial.print() 输出
- java - 尝试将文本文件作为参数传递时出错
- javascript - Jquery获取选中的项目返回未选中的框?
- javascript - VueJS:使用axios获取数据后未定义数组的属性
- python - 计算长度为 n 的随机数的实例
- python - Excel 文件未保存在 heroku 服务器上(Flask 应用程序)
- javascript - 一次激活一个按钮的切换
- envoyproxy - lua envoyFilter 在 istio-sidecar 中被忽略