Boat
Boat

Reputation: 535

Concatenate all array fields in a mongo document

Consider, we have a document like below;

{
    "name" : "ABC",
    "destination" : {
        "id" : "123",
        "place": "xyz"
    },
    "elements": [
        {
            "_id": "123",
            "name": "abc",
            "minorElements": [
                [{}, {}, {}, .....{}],
                [{}, {}, {}, .....{}],
                ...
            ],
            "majorElements": [
                [{}, {}, {}, .....{}],
                [{}, {}, {}, .....{}],
                ...
            ]
        }
    ]
}

How to write mongo db aggregation to concatenate all array fields and create a resultant document like;

"name" : "ABC",
"destination" : {
  "id" : "123",
  "place": "xyz"
},
{
  "elements": [{}, {}, {}, ..... {} ]  
  // elements contains all minorElements + majorElements + ...
}

Upvotes: 0

Views: 56

Answers (1)

Valijon
Valijon

Reputation: 13113

Does this meet your requirements?

db.collection.aggregate([
  {
    $addFields: {
      elements: {
        $reduce: {
          input: "$elements",
          initialValue: [],
          in: {
            $let: {
              vars: {
                elem: "$$this"
              },
              in: {
                $reduce: {
                  input: {
                    $objectToArray: "$$elem"
                  },
                  initialValue: [],
                  in: {
                    $concatArrays: [
                      "$$value",
                      {
                        $cond: [
                          {
                            $isArray: "$$this.v"
                          },
                          "$$this.v",
                          []
                        ]
                      }
                    ]
                  }
                }
              }
            }
          }
        }
      }
    }
  }
])

MongoPlayground

Upvotes: 1

Related Questions