how to concate all the members id from that mongodb collection?

Viewed 53

I have a collection named group on the mongoDb database . The collection includes 2 or more object and each object contains an array named members . what is the best possible and efficient way to concate and get all the members data from the database. what would be the mongoDB query ?

my collection looks like

[

    {
        id: ObjcetId("15215252"),
        groupName: "travellers of Bangladesh",
        members: ["1","2","3"]
    },
    {
        id: ObjcetId("32643724362"),
        groupName: "People from Bangladesh",
        members: ["4","5","6"]
    }
]

and i Want just this exact data

members: ["1","2","3","4","5","6"]

enter image description here

1 Answers

Use can use aggregations

  • $unwind to deconstruct the array
  • $group to reconstruct the array

Here is the code

db.collection.aggregate([
  { $unwind: "$members" },
  {
    $group: {
      _id: null,
      members: { $push: "$members" }
    }
  }
])

Working Mongo playground

Related