Read Documents: Part 5
Explore how to use MongoDB's array operators including $all, $elemMatch, and $size to perform complex queries on document arrays. Understand how to filter documents by matching multiple conditions on array values and embedded documents to refine your database reads.
We'll cover the following...
We'll cover the following...
Array operators
$all operator
The $all operator is used to match documents with the field containing all the values defined in it.
Let’s look at an example. First, we insert some documents in the terminal.
Next, we build a query using the $all operator to fetch documents with the tag urgent.
db.tasks.find({
tags: {
$all: ["urgent"]
}
});
This query returns the below output.
[
{
_id: ObjectId("60fa85c2384ee438a9eb2f9f"),
name: 'Task 1',
tags: [ 'urgent', 'not-important' ]
},
{
_id: ObjectId("60fa85c2384ee438a9eb2fa0"),
name: 'Task 2',
tags: [ 'urgent', 'important' ]
}
]
Notice that the query does not return the Task 3 document.
Let’s build another query using the $all operator to fetch documents that have both urgent and important tags.