1

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

1 Answer 1

1

Try $arrayElemAt to select first element from array

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

Playground

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

Comments

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.