Search⌘ K
AI Features

Read Documents: Part 4

Explore how to perform advanced read operations in MongoDB using key query operators. Understand checking field existence, data types, expression evaluation, regular expressions, and text search to filter documents based on complex conditions.

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: {
        $exists: 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: {
        $exists: 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 ...