...

/

Read Documents: Part 4

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.

Press + to interact
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.

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

Next, we ...