Example 1: Filtering Completed Tasks
We only want to retrieve users who have at least one completed task. We can achieve this using the $elemMatch projection operator:
db.users.find({ tasks: { $elemMatch: { completed: true } } })
Output:
[
{
"_id": ObjectId("60f9d7ac345b7c9df348a86e"),
"name": "Alice",
"tasks": [
{ "title": "Task 1", "completed": true },
{ "title": "Task 2", "completed": false },
{ "title": "Task 3", "completed": true }
]
},
{
"_id": ObjectId("60f9d7ac345b7c9df348a86f"),
"name": "Bob",
"tasks": [
{ "title": "Task 1", "completed": true },
{ "title": "Task 2", "completed": true },
{ "title": "Task 3", "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 “completed” field set to true.
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.