Element Query Operators

Introduction

Welcome back! You've done a fantastic job so far, mastering topics such as projections, comparison query operators, querying arrays and embedded documents, and logical query operators. Now, we're moving forward to explore another set of MongoDB query operators — Element Query Operators.

Element Query Operators Overview

Getting Hands Dirty with `$exists`

Delving into Data Types with `$type`

The $type operator allows you to query based on the BSON data type of the fields. This is particularly useful when dealing with documents that might have fields with varying data types.

For example, let's say the software developers have been inconsistent with the rating field in the database. Sometimes it's recorded as a string, like "Very good" or "Excellent", and other times it's recorded as a float number, like 8.7. To query documents based on the field type, you can do the following:

JavaScript
use comic_book_store_db

db.comic_books.find({ rating: { $type: "string" } }, { title: 1, rating: 1, _id: 0 })

In this example, $type is used to find documents where the rating field is of the string type. MongoDB returns all documents that match this criterion. The projection here displays only the title and rating fields, excluding the _id field.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal