Given the following MongoDB collection groups:
[{
_id: 'g1',
name: 'Group 1',
projects: [{
_id: 'p1',
name: 'Project 1',
tasks: [{
_id: 't1',
name: 'Task 1'
}, {
_id: 't2',
name: 'Task 2'
}]
}]
}]
I need to find task with _id = t2 and return the whole task object:
{
_id: 't2',
name: 'Task 2'
}
I'm able to find the group, either using mongodb:
db.groups.find({ 'projects.tasks._id': ObjectId('t2') })
Or with Mongoose:
Groups.findOne({ 'projects.tasks._id': 't2' })
But of course, this returns the entire group document, and not the task.
I've tried:
db.groups.aggregate([
{
$match: { 'projects.tasks._id': ObjectId('t2') }
}, {
$replaceRoot: {
newRoot: '$chapters.sections'
}
}
])
But this throws an error.