bc110402922
bc110402922

Reputation: 457

Convert multiple array into one array in MongoDB, also remove the None values from Arrays

Mongo DB Array Structure:

{

    "time" :[
           [2018-12-18T20:16:28.800Z , 2018-12-18T20:16:28.800Z, 2016-11-14T10:16:32.700Z],
           [2016-11-14T10:16:32.700Z, 2017-09-17T11:16:54.500Z, 2018-12-18T20:16:28.800Z],
           [2017-09-17T11:16:54.500Z, 2018-12-18T20:16:28.800Z, 2016-11-14T10:16:32.700Z]
],
    "bar": [
           [2,5,9,8],
           [6,3,7,None],
           [7,8,None]
    ]
}

Expected output with One array without None values:

"time" :[
2018-12-18T20:16:28.800Z, 
2018-12-18T20:16:28.800Z, 
2016-11-14T10:16:32.700Z,
2016-11-14T10:16:32.700Z, 
2017-09-17T11:16:54.500Z, 
2017-09-17T11:16:54.500Z, 
2016-11-14T10:16:32.700Z
],
    "bar": [
           2,
           5,
           9,
           6,
           3,
           7,
           8
]
}

I'm using Mongodb 4.2, and want to convert multiple arrays to one array, without $unwind. Because its reduce the performance in my case.

Upvotes: 1

Views: 1432

Answers (1)

turivishal
turivishal

Reputation: 36114

You can try,

  • time, $reduce to iterate loop of time and $concatArrays to merge the arrays
  • bar, $reduce to iterate loop of bar and $concatArrays to merge the arrays and get unique value, $filter to iterate loop of updated array from $reduce and remove None value from that array
db.collection.aggregate([
  {
    $project: {
      time: {
        $reduce: {
          input: "$time",
          initialValue: [],
          in: { $concatArrays: ["$$value", "$$this"] }
        }
      },
      bar: {
        $filter: {
          input: {
            $reduce: {
              input: "$bar",
              initialValue: [],
              in: { $concatArrays: ["$$value", "$$this"] }
            }
          },
          cond: { $ne: ["$$this", "None"] }
        }
      }
    }
  }
])

Playground

Upvotes: 1

Related Questions