Example 2: Filtering Tasks by Title
Suppose we want to filter tasks based on their title within the “tasks” array. We can use the dot notation to access fields within subdocuments and apply query conditions accordingly:
db.users.find({ "tasks.title": "Task 2" })
Output:
[
{
_id: ObjectId('60f9d7ac345b7c9df348a86f'),
name: 'Bob',
tasks: [
{ title: 'Task 1', completed: true },
{ title: 'Task 2', completed: true },
{ title: 'Task 3', completed: false }
]
},
{
_id: ObjectId('60f9d7ac345b7c9df348a870'),
name: 'Charlie',
tasks: [
{ title: 'Task 1', completed: false },
{ title: 'Task 2', completed: false }
]
},
{
_id: ObjectId('60f9d7ac345b7c9df348a871'),
name: 'David',
tasks: [
{ title: 'Task 1', completed: true },
{ title: 'Task 2', completed: true },
{ title: 'Task 3', completed: true },
{ title: 'Task 4', completed: false }
]
}
]
This query will return documents where at least one task within the “tasks” array has the title “Task 2”.
How to Filter Array in Subdocument with MongoDB?
In MongoDB, working with arrays within subdocuments is a common requirement in many applications. Filtering and manipulating arrays efficiently can significantly enhance the flexibility and enhance our queries.
In this article, we’ll explore how to filter arrays within subdocuments in MongoDB by covering essential concepts and providing detailed examples with outputs to understand these techniques effectively.
Contact Us