AI Features

Read Documents: Part 4

Learn and practice commands like find, findOne with elements operator and evaluation operators into the filter query.

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.

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