mongodb - 如果它是一个数组,如何连接字符串数组字段以显示为一个字符串

标签 mongodb pdi

以下是我收藏的两份文件:

{
    "_id": {
        "$oid": "5f48e358d43721376c397f54"
    },
    "heading": "this is heading",
    "tags": ["tag1","tag2","tag3"],
    "categories": ["projA", "projectA2"],
    "content": ["This", "is", "the", "content", "of", "the", "document"],
    "timestamp": 1598612312.506219,
    "lang": "en"
}

{
    "_id": {
        "$oid": "5f48e358d43721376c397f53"
    },
    "heading": "this is heading",
    "tags": "tag1,tag2,tag3",
    "categories": "projA, projectA2",
    "content": "This is the content of the document",
    "timestamp": 1598612312.506219,
    "lang": "en"
}

我想编写一个查询,连接第一个文档的 content 元素并按原样打印第二个(因为它不是数组)。

我正在使用以下脚本来连接,但它在第二个文档上给出了错误,说它需要是一个数组,但事实并非如此。我不知道如何在这种情况下使用 switch 语句或嵌套 if 条件:

    "$addFields": {
  content: { 
      "$reduce": {
        "input": "$content",
        "initialValue": "",
        "in": {
          "$cond": {
            "if": { "$eq": [ { "$indexOfArray": [ "$content", "$$this" ] }, 0 ] },
            "then": { "$concat": [ "$$value", "$$this" ] },
            "else": { "$concat": [ "$$value", "\n", "$$this" ] }
          }    
        }
      }        
    }
}

我是 mongo DB 的新手,所以我们将不胜感激。

最佳答案

你可以试试,

  • $cond 检查内容类型是否为数组,$reduce 连接内容字符串,$trim 删除空格<
db.collection.aggregate([
  {
    $addFields: {
      content: {
        $cond: [
          { $eq: [{ $type: "$content" }, "array"] },
          {
            $trim: {
              input: {
                $reduce: {
                  input: "$content",
                  initialValue: "",
                  in: { $concat: ["$$value", " ", "$$this"] }
                }
              }
            }
          },
          "$content"
        ]
      }
    }
  }
])

Playground

关于mongodb - 如果它是一个数组,如何连接字符串数组字段以显示为一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64820258/

相关文章:

node.js - 更新 Mongoose 中的模式以添加新属性

Ruby 按键值分组哈希

mongodb - 如何汇总和平均两个日期之间的时间?

regex - 使用 Pentaho 删除特殊字符 - 替换为字符串

postgresql - Pentaho 数据集成输入/输出位类型错误

PDI 中的 MySQLNonTransientConnectionException

mongodb - 当使用mongo-connector进行管道传输时,elasticsearch 6不允许多种类型

ruby-on-rails - 每秒 MacOS 唤醒错误

java - 无法连接 Windows 10 上安装的 Pentaho PDI 中的步骤