1
[
  {
    "data": {
      "id": "123",
      "name": "delta1"
    },
    "property_data": [
      {
        "ser_name": "Insights",
        "ser_value": "10000"
      },
      {
        "ser_name": "plans",
        "ser_value": "50000"
      }
    ]
  }
]

Explanation : property_data is an array. data is an object. Need to transform Array into an object, but the problem is if I do $unwind on property_data I get multiple times data objects, which I needed only once. I want to convert my data structure, into multiple documents but data should not be repeated again and again

Expected Output

[
  {
    "property_data": {
     "id": "123",
      "name": "delta1"
    }
  },
  {
    "property_data": {
      "ser_name": "Insights",
      "ser_value": "10000"
    }
  },
  {
    "property_data": {
      "ser_name": "plans",
      "ser_value": "50000"
    }
  },
]

1 Answer 1

1

This can be achieved with some basic structure manipulation, like so:

db.collection.aggregate([
  {
    $project: {
      property_data: {
        "$concatArrays": [
          "$property_data",
          [
            "$data"
          ]
        ]
      }
    }
  },
  {
    $unwind: "$property_data"
  },
  {
    $replaceRoot: {
      newRoot: {
        property_data: "$property_data"
      }
    }
  }
])

Mongo Playground

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

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.