Search code examples
arraysmongodbmongodb-queryaggregation-frameworkmongodb-lookup

MongoDB aggregation make inner array in root


Hi I have two collection person and department. Those collection have the properties as below.

I want to aggregate and add a inner array in to the root of the document. Please check the result I need below:

person:

{
  _id:ObjectID("5ff93b43535bera64de4"),
  first_name: some name,
  last_name : some name,
  dept: department1,

}

department:

{
  dept_name: department1,
  dept_descp : this is description,
  books: [
          {
           book_name: book1,
           subject: subject1,
           },
            {
           book_name: book2,
           subject: subject2,
           },
         ]
}

So far I have tried but I didn't get the needed result

person.aggregate([
   {
   $match:
        {
            "_id": ObjectId("5ff93b43535bera64de4")
        }
    },
   {
        $lookup: {
            from: "department",
            localField: "dept",
            foreignField: "dept_name",
            as: "ndept"
        }
   },
   {
     $project:{"books": '$ndept.books'}
   }
   ])

the result I would like to get is

Result:

{
  _id:ObjectID("5ff93b43535bera64de4"),
  first_name: some name,
  last_name : some name,
  dept: department1,
  books: [
          {
           book_name: book1,
           subject: subject1,
           },
            {
           book_name: book2,
           subject: subject2,
           }
         ]
}

Solution

  • Try $arrayElemAt to select first element from array

    {
      $addFields: {
        books: { $arrayElemAt: ["$ndept.books", 0] }
      }
    }
    

    Playground