0

I am new to Mongodb and don't know much about aggregates how do I change below object to desired single array of object.

[
  {
    id: "1",
    title: "First Title",
    des: "This is desc",
    contents: [
      {
        id: "1",
        title: "content-1 title",
        des: "This is desc"
      },
      {
        id: "2",
        title: "Content-2 title",
        des: "This is desc"
      }
    ]
  },
  {
    id: "2",
    title: "Second Title is Here",
    des: "This is desc",
    contents: [
      {
        id: "1",
        title: "content-1 title",
        des: "This is desc"
      },
      {
        id: "2",
        title: "Content-2 title",
        des: "This is desc"
      }
    ]
  }
]

My Desired Out Single array :

[
  {
    id: "1",
    title: "First Title",
    des: "This is desc"
  },
  {
    id: "1",
    title: "content-1 title",
    des: "This is desc"
  },
  {
    id: "2",
    title: "Content-2 title",
    des: "This is desc"
  },
  {
    id: "2",
    title: "Second Title is Here",
    des: "This is desc"
  },
  {
    id: "1",
    title: "content-1 title",
    des: "This is desc"
  },
  {
    id: "2",
    title: "Content-2 title",
    des: "This is desc"
  }
]

1 Answer 1

1
db.collection.aggregate([
  {
    $set: {
      contents: {
        $concatArrays: [
          [
            {
              id: "$id",
              title: "$title",
              des: "$des"
            }
          ],
          "$contents"
        ]
      }
    }
  },
  {
    $unwind: "$contents"
  },
  {
    $replaceWith: "$contents"
  }
])

mongoplayground

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

4 Comments

Wow Great Answer. But still have some issue, all contents should be shown below main object. order is changed in result. also need to sort according to top one id
I update my answer to solve the problem of order changing. If you want to have only one object instead of six, you can group them all. Add $sort stage after $unwind` stage can sort documents.
mongoplayground link now did't work
@RammeharSharma ok I fix it

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.