Example 3: Filtering Completed Tasks Count
If we want to filter users based on the count of completed tasks, we can use the $size operator to match arrays with a specific number of elements:
db.users.find({ tasks: { $size: 2 } })
Output
[
{
_id: ObjectId('60f9d7ac345b7c9df348a870'),
name: 'Charlie',
tasks: [
{ title: 'Task 1', completed: false },
{ title: 'Task 2', completed: false }
]
}
]
This query will return documents where the “tasks” array contains exactly two elements.
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