MongoDB 查找并映射 2 个结果数组
Posted
技术标签:
【中文标题】MongoDB 查找并映射 2 个结果数组【英文标题】:MongoDB lookup and map 2 arrays of result 【发布时间】:2021-07-19 18:16:10 【问题描述】:我在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。请提出建议。
【问题讨论】:
【参考方案1】:$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
Playground
【讨论】:
以上是关于MongoDB 查找并映射 2 个结果数组的主要内容,如果未能解决你的问题,请参考以下文章
NestJS TypeORM MongoDB 无法使用 find 或 FindOne 搜索存储库
MongoDB - 查找 - 多个集合 - 结果在一个数组中