Home > other >  How do I create a single array of object from nested array of obejcts mongodb aggregate?
How do I create a single array of object from nested array of obejcts mongodb aggregate?

Time:04-07

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"
  }
]

CodePudding user response:

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

mongoplayground

  • Related