Search⌘ K
AI Features

Read Documents: Part 4

Explore how to perform advanced document queries in MongoDB using element operators such as $exists and $type, along with evaluation operators like $expr, $regex, and $text. Understand how to filter documents based on field existence, data types, pattern matching, and text search. This lesson equips you with techniques to refine your MongoDB queries for more precise data retrieval.

Element operators

$exists operator

The $exists operator is used to check the existence of a field and return documents.

Let’s insert some documents to use with the$exists operator query.

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

Next, we build a query to return a document that has a field value set to priority.

db.tasks.find({
    priority: {
        $exist: true
    }
});

This query returns the below output.

[
  {
    _id: ObjectId("60fa599e384ee438a9eb2f96"),
    name: 'Task 1',
    priority: 1
  }
]

It doesn’t return Task 2.

Let’s build a query to return a document that does not have a priority field value.

db.tasks.find({
    priority: {
        $exist: false
    }
});

This query returns the below output.

[
  {
    _id: ObjectId("60fa599e384ee438a9eb2f97"),
    name: 'Task 2',
    status: 'pending'
  }
]

It doesn’t return Task 1.

$type operator

We use the $type operator to check the type of the field, and return documents if a match is found.

Let’s insert some documents.

Markdown
db.tasks.insertMany([
{
name: 'Task 1',
due_date: new Date(),
priority: 1,
categories: [
{
key: 'category_a'
},
{
key: 'category_b'
}
]
}
]);
...