Arrays 如何拆分包含逗号和更新为独立元素的字符串数组?

Arrays 如何拆分包含逗号和更新为独立元素的字符串数组?,arrays,mongodb,Arrays,Mongodb,我有如下mongo收集数据: { "tag1" : { "tag2" : [ "test,test1", "sample" ] } } 我需要更新集合,该集合在tag2数组中具有“test,test1”值,并更新为单独的元素“test”,“test1”,因此结果应该如下所示: { "tag1" : { "tag2"

我有如下mongo收集数据:

{
  "tag1" : {
    "tag2" : [ 
      "test,test1",
      "sample"
    ]
  }
}
我需要更新集合,该集合在
tag2
数组中具有
“test,test1”
值,并更新为单独的元素
“test”
“test1”
,因此结果应该如下所示:

{
  "tag1" : {
    "tag2" : [ 
      "test",
      "test1",
      "sample"    
    ]
  }
}
MongoDB版本:3.6

谢谢。

你可以试试

  • $reduce
    迭代循环
  • $split
    按“,”拆分字符串
  • $concatarray
    到concat当前数组和拆分字符串的数组
  • $out
    克隆新集合中的所有更新文档

谢谢。我已经更新了问题。事实上,我想更新我在问题中提到的所有记录。我已经更新了答案,您可以检查,使用$out,我认为查询mongodb 3.6中没有其他选项,否则,您必须在检索记录后通过js代码手动执行。@Venugopalsetharaman在提供的答案中是否有您认为无法解决您问题的内容?如果是,请对答案进行评论,以澄清哪些问题需要解决,哪些问题尚未解决。如果它确实回答了您提出的问题,那么请注意您提出的问题
db.collection.aggregate([
  {
    $addfields: {
      "tag1.tag2": {
        $reduce: {
          input: "$tag1.tag2",
          initialValue: [],
          in: {
            $concatArrays: ["$$value", { $split: ["$$this", ","] }]
          }
        }
      }
    }
  },
  { $out: "empty collection name" }
])