...

/

Read Documents: Part 5

Read Documents: Part 5

Learn and practice array operators.

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.

Press + to interact
db.tasks.insertMany([
{
name: 'Task 1',
tags: ["urgent", "non-important"],
},
{
name: 'Task 2',
tags: ["urgent", "important"],
},
{
name: 'Task 3',
tags: ["non-urgent", "non-important"],
}
]);

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. ...