$in, $nin, $implicit in MongoDB: Examples and Usage🔥

RMAG news

Understanding $implicit

Let’s first understand how $implicit works. Suppose you’re asked to fetch data for individuals aged more than 18 and less than 30. How would you do that? Let’s explore through an example:

Imagine we have a database named school with a collection called students.

db.students.find({ age: { $gte: 18, $lte: 30 } });

db.students indicates that we are working with the students collection.
The find method is used to search for all the matching data.

{ age: { $gte: 18, $lte: 30 } } is the search criteria, which specifies that we are looking for documents where the age is greater than or equal to 18 and less than or equal to 30.

Using $in

Now, suppose you are asked to fetch data for individuals aged 18, 20, 10, and 4. You can easily achieve this using $in. Let’s understand through an example:

db.students.find({ age: { $in: [18, 20, 10, 4] } }, { age: 1 });

db.students indicates that we are working with the students collection.
The find method is used to search for all the matching data.

{ age: { $in: [18, 20, 10, 4] } } is the search criteria, specifying that we are looking for documents where the age matches any of the values in the array [18, 20, 10, 4].

{ age: 1 } specifies that only the age property will be shown in the results.

Using $nin

$nin is the opposite of $in. In this case, you will get all data except for the values you provide. For example:

db.students.find({ age: { $nin: [18, 20, 10, 4] } }, { age: 1 });

{ age: { $nin: [18, 20, 10, 4] } } is the search criteria, specifying that we are looking for documents where the age does not match any of the values in the array [18, 20, 10, 4].

{ age: 1 } specifies that only the age property will be shown in the results.

Feel free to check out my GitHub Kawsar Kabir and connect with me on LinkedIn.