Mongodb - 连接多个嵌套数组并转换为字符串

Mongodb - Concatenate multiple nested arrays and convert to a string

我有以下文件

{"_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 服务器上执行此操作的最佳方法是什么?有这样的方法吗?

查询

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

*检查 if not 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"]}])