If you are looking for “MongoDB: How to Use Not Equal by inTecSols”. Then you can easily find different scenarios with examples here:

Let’s discus about some different operators for querying results with “NOT EQUAL” and “NOT IN” in MongoDB.

  1. $ne (Not Equal)
  2. $nin (Not In)

These are the available methods to exclude certain matched from results. If you want to exclude result which is “Not Equal” to certain query then you can simply follow this method:

“$ne” = “Not Equal”:

db.collection.find({'carName':{$ne: 'toyota'}});

If you want to exclude results which are “Not In” certain queries then you can simply follow this method:

“$nin” = “Not In”:

db.collection.find({'carName':{$nin: ['toyota','honda','audi']}});

Let’s  explore it more by adding some entries to collection named as “cars” with few car names “toyota, honda, audi, bmw, suzuki and hundayi”. You can also follow this step to enter new records in your collection(cars).

db.cars.insertOne({carName: 'toyota',active: true})
db.cars.insertOne({carName: 'honda',active: true})
db.cars.insertOne({carName: 'audi',active: true})
db.cars.insertOne({carName: 'bmw',active: true})
db.cars.insertOne({carName: 'suzuki',active: true})
db.cars.insertOne({carName: 'hundayi',active: true})

Now you have entries in your collection(cars). So let’s go to examples without wasting time.

Example 1: $ne “Not Equal” query

You can call this method to find results where carName is Not Equal to “toyota” $ne is the operator which can help you to get your desired results.

db.cars.find({'carName':{$ne: 'toyota'}});

Ouput

{
"_id": "63d2ccaf1f12a55c0cc7492b",
"carName": "honda",
"active": true
},
{
"_id": "63d2ccaf1f12a55c0cc7493b",
"carName": "audi",
"active": true
},
{
"_id": "63d2ccaf1f12a55c0cc7494b",
"carName": "bmw",
"active": true
},
{
"_id": "63d2ccaf1f12a55c0cc7495b",
"carName": "suzuki",
"active": true
},
{
"_id": "63d2ccaf1f12a55c0cc7496b",
"carName": "hundayi",
"active": true
}

Example 2: $nin “Not In” query

If you want to get results which are Not In “toyota, honda and audi” then you need to use $nin operator to get certain results.

db.cars.find({'carName':{$nin: ['toyota','honda','audi']}});

Output

{
"_id": "63d2ccaf1f12a55c0cc7494b",
"carName": "bmw",
"active": true
},
{
"_id": "63d2ccaf1f12a55c0cc7495b",
"carName": "suzuki",
"active": true
},
{
"_id": "63d2ccaf1f12a55c0cc7496b",
"carName": "hundayi",
"active": true
}

This is the easiest way to aggregate results using $ne or $nin

I hope this lesson helps you a lot to learn about “How to use Not Equal and Not In MongoDB“. If you learned from intecsols.com then don’t forget to share it with others and subscribe our Youtube Channel

Note: If you still uncleared about $ne then you can see complete documentation at MongoDB

Note: If you still uncleared about $nin then you can see complete documentation at MongoDB

LEAVE A REPLY

Please enter your comment!
Please enter your name here