【问题标题】:MongoDB: Aggregate function returns the output of strings as a single array. How can they be converted into individual arraysMongoDB:聚合函数将字符串的输出作为单个数组返回。如何将它们转换为单独的数组
【发布时间】:2018-12-24 04:07:09
【问题描述】:

我用过的聚合函数:-

User.aggregate([
 {
  "$project": {
    "_id": 0,
    "DescriptionArray": {
      "$reduce": {
        "input": "$services.description",
        "initialValue": [],
        "in": {
          "$concatArrays": [
            "$$this",
            "$$value"
          ]
        }
      }
    },
    "PicArray": {
      "$reduce": {
        "input": "$services.pic",
        "initialValue": [],
        "in": {
          "$concatArrays": [
            "$$this",
            "$$value"
          ]
        }
      }
    }
   }
}
])

以下列方式给我输出:-

[ { DescriptionArray:
 [ 'Des1',
   'Des2',
   'Des3',
   'Des4' ],
PicArray:
 [ 'Pic1.jpeg',
   'Pic2.jpeg',
   'Pic3.jpeg',
   'Pic4.jpeg' ] },
{ DescriptionArray:
 [ 'Des5',
   'Des6' ],
PicArray: [ 'Pic5.jpeg', 'Pic6.jpeg' ] } ]

但我希望输出的格式是每个元素都被视为一个单独的数组,而不是按以下方式由许多元素组成的单个数组:-

 [
  { DescriptionArray: [ 'Des1' ],
   PicArray: [ 'Pic1.jpeg' ],
 },
 { DescriptionArray: [ 'Des2' ],
  PicArray: [ 'Pic2.jpeg' ],
 },
{ DescriptionArray: [ 'Des3' ],
  PicArray: [ 'Pic3.jpeg' ],
 },
{ DescriptionArray: [ 'Des4' ],
  PicArray: [ 'Pic4.jpeg' ],
 },
{ DescriptionArray: [ 'Des5' ],
  PicArray: [ 'Pic5.jpeg' ],
 },
{ DescriptionArray: [ 'Des6' ],
  PicArray: [ 'Pic6.jpeg' ],
 }
]

为了以上述方式获得输出,可以做些什么?

【问题讨论】:

    标签: mongodb mongoose nosql mongodb-query aggregation-framework


    【解决方案1】:

    您可以在 3.4 及更高版本中使用以下聚合查询。

    User.aggregate([
      {"$project":{
        "array":{
          "$map":{
            "input":{"$range":[0,{"$size":"$services.description"}]},
            "as":"ix",
            "in":{
             "DescriptionArray":{"$arrayElemAt":["$services.description","$$ix"]},
             "PicArray":{"$arrayElemAt":["$services.pic","$$ix"]}}
          }
        }
      }},
      {"$unwind":"$array"},
      {"$replaceRoot":{"newRoot":"$array"}}
    ])
    

    【讨论】:

    • 谢谢!像魅力一样工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    相关资源
    最近更新 更多