Question

I have a collection "Course" with this structure:

{ 
  Lessons: [ 
  {
     Title: 'xxx',
     Contents: [ 
     {
       Title: 'yyy',
     },
     ...
     ]
  },
  ...
  ]
}

How can I retrieve the list of Titles of all Contents using MongoDB's aggregation pipeline?

I managed to $unwind all contents this way:

db.Course.aggregate( { $unwind : '$Lessons' }, { $unwind : '$Lessons.Contents' } )

But I can't manage to filter only the Titles within each Content.

Was it helpful?

Solution

You are very close. If I got your requirement right you just need to add a projection:

db.Course.aggregate( 
  { $unwind : "$Lessons" }, 
  { $unwind : "$Lessons.Contents" }, 
  { $project: { _id: 0, test: "$Lessons.Contents.Title" } } 
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top