【发布时间】:2020-09-19 07:59:52
【问题描述】:
我有两个这样的集合:
# col1
[
{
_id: '5ec878f79c87a300127ec503',
name: 'dim'
},
{...},
]
# col2
[
{
_id: ObjectId('5ec8da619c87a30012f41d0b'),
record_id: '5ec878f79c87a300127ec503',
tags: 'authenticated'
},
{
_id: ObjectId('5ec8da619c87a30012ffdsk1'),
record_id: '5ec878f79c87a300127ec503',
tags: 'pre'
},
]
我想将两个集合合二为一并将 col2._id 从 objectid 转换为字符串。
这是我的汇总查询:
col1.aggregate(
[
{'$lookup': {
'from': 'col2',
'localField': '_id',
'foreignField': 'record_id',
'as': 'records'
}},
{'$project': {'records._id': {'$toString': '$records._id'}}}
]
)
我的结果应该是这样的:
# result
[
{
'_id': '5ec878f79c87a300127ec503',
'name': 'dim',
'records': [
{
'_id': '5ec8da619c87a30012f41d0b',
'record_id': '5ec878f79c87a300127ec503',
'tags': 'authenticated'
},
{
'_id': '5ec8da619c87a30012ffdsk1',
'record_id': '5ec878f79c87a300127ec503',
'tags': 'pre'
},
]
}
]
但我遇到了错误。
Unsupported conversion from array to string in $convert with no onError value
我也试过 $addFields 和 $map。它要么覆盖记录并返回一个数组,要么创建一个新字段。这不是我想要的。
{'$addFields': {
'records': {
'$map': {
'input': '$records',
'as': 'r',
'in': {'$toString': '$$r._id'}
}
}
}}
所以我的问题是:如何在聚合期间将 col2._id 从 objectid 转换为字符串?
【问题讨论】:
-
可以使用聚合运算符$toString。
-
我试过了,问题是子集合
-
你应该使用
$lookup的管道进行匹配——在这种情况下。 -
您必须在
records数组上使用$map- 您已经发布了一些代码。它需要一些修正。使用$mergeObjects 将现有字段与转换后的_id字段合并(即在应用$toString之后)。 -
在您的
$addFields阶段,$map的in参数值应为:in: { $mergeObjects: [ "$$r", { "_id": { $toString: "$$r._id" }} ] }。这是您的解决方案。