将 mongo 数据库数组投影为命令分隔字符串

问题描述 投票:0回答:1

我有以下收藏

{
  "_id": "12345",
  "Products": [
    "Product1",
    "Product2"
  ],
  "State": "active",
}

并希望将其投影为类似于下面的输出

_id: "12345"
Products: "Product1, product2"

我尝试了这个,但我没有得到所需的命令分隔连接字符串的输出

{
  _id: 1,
  Products: { 
      $reduce: { 
          input: "$Products", 
          initialValue:"0" ,
          in: {concat:  ["$$value", "$$this"] } 
      }
  }
}
arrays mongodb concatenation projection
1个回答
0
投票

您可以使用

$reduce
$concat
将值连接成一个字符串。需要使用
$cond
来确定值之间是否需要逗号。

db.collection.aggregate([
  {
    "$project": {
      "_id": 1,
      "Products": {
        $reduce: {
          input: "$Products",
          initialValue: "",
          in: {
            $concat: [
              "$$value",
              {
                $cond: [
                  {
                    $eq: [
                      "$$value",
                      ""
                    ]
                  },
                  "",
                  ","
                ]
              },
              "$$this"
            ]
          }
        }
      }
    }
  }
])
© www.soinside.com 2019 - 2024. All rights reserved.