Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb $concat与查找字段?_Mongodb_Aggregation Framework - Fatal编程技术网

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的?整晚加班我想。。。