1

I have a document structure with arbitrarily nested arrays similar to follows, which I want to flatten during an aggregation pipeline:

{ 
  "data": [
    "one",
    [
      "two", 
      "three"
    ],
    [
      [ "four" ],
      [ "five" ]
    ]
  ]
}

Expected result:

{ "data": [ "one", "two", "three", "four", "five" ] }

Existing question here gives some ideas (especially this answer), however not totally generically with an arbitrary depth of nesting.

Is there some more generic solution to this?

2 Answers 2

2

MongoDB doesn't provide any looping or recursion, so doing anything arbitrarily many times is simply not possible.

You could programmatically build an aggregation pipeline in the client that could flatten an array dozens of levels deep, but the overall pipeline must fit within an 16MB request document, so it won't support arbitrary depth.

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

Comments

1

I agree with @Joe's answer, No straight way to handle this kind of operation in MongoDB, You should think about your schema design as per your query requirement.

If you think you really needed this, you can try MongoDB Defines a custom aggregation function or expression in JavaScript, ​$function and $accumulator,

{
  $project: {
​    data: {
      ​$function: {
        ​body: function(data) {
          ​const flatten = arr => arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
          ​return flatten(data);
        ​},
        ​args: ["$data"],
        ​lang: "js"
      ​}
    ​}
  ​}
​}

Playground

IMPORTANT

Executing JavaScript inside an aggregation expression may decrease performance. Only use the $function operator if the provided pipeline operators cannot fulfill your application's needs.

Comments

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.