Mongodb $concat与查找字段?
我正在尝试Mongodb $concat与查找字段?,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我正在尝试$concatMongoDB聚合中的一些字段。问题是它们来自$lookup,显然它们不能像那样连接在一起。以下是我正在尝试的: { $lookup: { from: 'users', localField: 'user_id', foreignField: '_id', as: 'user' } }, { $projec
$concat
MongoDB聚合中的一些字段。问题是它们来自$lookup
,显然它们不能像那样连接在一起。以下是我正在尝试的:
{
$lookup: {
from: 'users',
localField: 'user_id',
foreignField: '_id',
as: 'user'
}
},
{
$project: {
'fullname': { $concat: ['$user.lastname', ', ', '$user.firstname' ] }
}
}
这将导致以下错误消息:
$concat only supports strings, not array
有趣的是,如果我使用$concatarray
,消息将是:
$concatArrays only supports arrays, not string
那么我如何引用
$concat
中的查找字段呢?这是因为user
从
当您知道只有一个结果时使用:
{ "$project": {
"fullname": {
"$let": {
"vars": { "user": { "$arrayElemAt": ["$user",0] },
"in": { "$concat": [ "$$user.lastname", ", ", "$$user.firstname" ] }
}
}
}}
或者,如果您有多个:
{ "$unwind": "$user" },
{ "$project": {
"fullname": { "$concat": [ "$user.lastname", ", ", "$user.firstname"' ] }
}}
输出是一个数组,即使它只是一个结果或多个结果,甚至没有结果。因此,您需要使用适当的运算符来处理is。这是因为
用户
从
当您知道只有一个结果时使用:
{ "$project": {
"fullname": {
"$let": {
"vars": { "user": { "$arrayElemAt": ["$user",0] },
"in": { "$concat": [ "$$user.lastname", ", ", "$$user.firstname" ] }
}
}
}}
或者,如果您有多个:
{ "$unwind": "$user" },
{ "$project": {
"fullname": { "$concat": [ "$user.lastname", ", ", "$user.firstname"' ] }
}}
输出是一个数组,即使它只是一个结果或多个结果,甚至没有结果。因此,您需要使用合适的操作员来处理is。Yay!下一个问题:我是如何忘记$unwind和$group的?整晚加班我想…耶!下一个问题:我是如何忘记$unwind和$group的?整晚加班我想。。。