【问题标题】:Mongodb - Concatenate multiple nested arrays and convert to a stringMongodb - 连接多个嵌套数组并转换为字符串
【发布时间】:2022-01-06 14:29:02
【问题描述】:

我有以下文件

{"_id": "1", "posts": [{"text": "all day long I dream about", "datetime": "123"}, {"text": "all day long ", "datetime": "321"}]}
{"_id": "1", "posts": [{"text": "all day long I dream about", "datetime": "123"}, {"text": "all day long ", "datetime": "8888"}, {"text": "I became very hungry after watching this movie...", "datetime": "8885"}]}

我希望将 text 字段连接到一个新字段,将 datetime 字段连接到一个新字段,同时还将数组元素连接到一个字符串中,新字段如下

{"_id": "1", "text": "all day long I dream about, all day long ", "datetime": "123, 321"}
{"_id": "1", "text": "all day long I dream about, all day long ,I became very hungry after watching this movie... ", "datetime": "123, 8888, 8885"}

直接在 Mongodb 服务器上执行此操作的最佳方法是什么?有没有这样的方法?

【问题讨论】:

    标签: mongodb concatenation


    【解决方案1】:

    查询

    • 减少以null 开头的帖子(相同的代码 2x)
    • 如果不为空(concat all_string ", " current_string)
    • else current_string(这只发生在第一个字符串中)

    *检查是否不是null 仅适用于第一个字符串,没有像“,string1,string2 ...”这样的东西。我们这样做是为了避免将, 添加到第一个字符串
    *你也可以用 1 个 reduce 来做,但是代码会更复杂

    Test code here

    aggregate(
    [{"$set":
      {"text":
       {"$reduce":
        {"input":"$posts",
         "initialValue":null,
         "in":
         {"$cond":
          ["$$value", {"$concat":["$$value", ", ", "$$this.text"]},
           "$$this.text"]}}}}},
     {"$set":
      {"datetime":
       {"$reduce":
        {"input":"$posts",
         "initialValue":null,
         "in":
         {"$cond":
          ["$$value", {"$concat":["$$value", ", ", "$$this.datetime"]},
           "$$this.datetime"]}}}}}
     {"$unset":["posts"]}])
    

    【讨论】:

    • 完美运行,您的解释是有福的。谢谢。
    • 假设我想创建一个新的 'datetime' 字符串,即使所有值都为空,例如 - "null, null, null..." 我该怎么做?跨度>
    • 我认为你需要 this ,它使用一个变量,如果 datetime 为 null ,那么它就是 "null" ,否则有正常的 datetime 值。
    • 你是个魔术师。非常感谢你,你帮了我很多。
    猜你喜欢
    • 2020-05-04
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多