我有两个相关的 mongo 集合。这些示例文档说明了它们的关系:
// "things" collection example document:
{
_id: 1,
categories: [123, 234],
// other fields
}
// "categories" collection example documents:
{
_id: 123,
value: "Category name"
},
{
_id: 234,
value: "Other category name"
}
我一直在尝试找到一种方法,将文档类别数组中的 ID 号映射things
到集合中相应文档的值categories
。根据上述示例,您最终将得到以下文档:
{
_id: 1,
categories: [
"Category name",
"Other category name",
],
// other fields
}
我的问题是我当前的管道过于复杂,并且肯定会执行不必要的操作,从而造成潜在的性能问题。我当前的管道是:
- (起点)
{
_id: 1,
categories: [123, 234],
// other fields
}
$unwind
类别
{
_id: 1,
categories: 123,
// other fields
},
{
_id: 1,
categories: 234,
// other fields
}
$lookup
在类别集合上将新的本地“类别”字段与外部“_id”匹配
{
_id: 1,
categories: [{ _id: 123, value: "Category name" }],
// other fields
},
{
_id: 1,
categories: [{ _id: 234, value: "Other category name" }],
// other fields
}
$addFields
用{ $arrayElemAt: [ "$categories", 0 ] }
我最初想要的文档替换数组
{
_id: 1,
categories: { _id: 123, value: "Category name" },
// other fields
},
{
_id: 1,
categories: { _id: 234, value: "Other category name" },
// other fields
}
$addFields
使用{ categories: "$categories.value" }
值字段替换整个文档
{
_id: 1,
categories: "Category name",
// other fields
},
{
_id: 1,
categories: "Other category name",
// other fields
}
$group
“撤消”原始展开。我使用_id: "$_id"
和{ $addToSet: "$categories" }
(以及格式中的许多其他属性<field-name>: { $first: "$<field-name>" }
来重新添加所有“其他字段”)
{
_id: 1,
categories: [
"Category name",
"Other category name",
],
// other fields
}
我担心我缺少效率更高的聚合函数,因此当我将来在大量文档上使用它时,会产生缓慢且昂贵的读取操作,但我找不到更干净的解决方案。任何正确的方向的推动都将不胜感激。