Search⌘ K

Read Documents: Part 3

Explore how to use MongoDB logical operators such as $and, $or, $not, and $nor to create complex queries. Understand how these operators combine or exclude conditions to filter documents, helping you retrieve data based on multiple criteria accurately.

Logical operators

Logical operators are used to combine more than one operator. It returns the documents accordingly.

$and operator

The $and operator is used to join multiple conditions. All the conditions must be true for a successful match. We use this operator to apply one or more conditions and return documents that match all the conditions.

Let’s insert documents so we can build the $and operator query.

Markdown
db.tasks.insertMany([
{
name: 'Task 1',
priority: 1,
status: 'pending',
},
{
name: 'Task 2',
priority: 1,
status: 'completed',
},
{
name: 'Task 3',
priority: 2,
status: 'pending',
}
]);

Next, we build a query that returns documents with priority: 1 and the status: ‘pending’.

db.tasks.find({
    $and: [
        {
            priority: 1,
        },
        {
            status: 'pending',
        }
    ]
});

This ...