0

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.

2
  • Notice that there are multiple groups, each with multiple projects, each with multiple tasks. I don't have the _id of the parent group or project, only the _id of the task. Commented Dec 19, 2022 at 12:55
  • 1
    Does this answer your question? How to query in a nested array and project only the matching items from array? Commented Dec 19, 2022 at 14:57

0

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.