Mongodb Aggregate: Combine multiple keys into an array

Viewed 217

I want to combine three keys in my documents to an array using mongodb aggregate. Here is an example of what I am trying to accomplish:

Input Document:

{  
    _id: "xyz", 
    p1: "A", 
    p2: "E", 
    p3: "C"
}

Output Document:

{ 
   _id: "xyz",
   p: ["A", "E", "C"] 
}

Does anyone have an idea how to accomplish this using mongodb aggregate?

Cheers J

1 Answers

Using aggregation's $project stage, You can do as like below :

db.collection.aggregate([
  {
    $project: { p: [ "$p1", "$p2", "$p3" ] }
  }
])

Test : mongoplayground

Related