1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the answer, but after this condition, I'm not getting repeated values, bar contains the multiple repeated values inside the array. just want to exclude the "None"
Okay got it i looked at your expected that was unique that's why i used $setUninon.
Thanks, Its work for me. I get multiple documents. how I can make one? document 1: { _id: abcdef, name: "foo", time: [1234], doc: [1234] } document 2 { _id: alexa, name: "alexa", time: [1234], doc: [1234] } Expected output { time[1234], alexa[1234], foo[1234] }
You mean you need to combine all documents in single? just share a playground link with your data.
playground. yes, I want to combine all documents into single documents.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.