How To Get Documents From MongoDB except One: $nin

In situations where you need to get documents excluding some specific values, as a beginner, you will extract all documents and use javascript to filter. But that’s not the ideal way to do this. MongoDB gifted us with a really powerful operator that can help us make a mongo query for the same. Benefits of using the operator include less code, better performance. The operator is $nin

$nin accepts an array of values for a particular key in the document schema. All the documents that will match the keys in the $nin array will be excluded from the results. Let’s take an example: we have a schema Exclusion and we want to get all the documents in this document except the ones whose value key matches our array of values.

Exclusion.find(value: {$nin: [1,2]})

This is a simple use case of fetching data. But what if you want to update some data in the collection except some documents. Here is a query to explain just that:

Exclusion.update({name: {$nin:["Amigo", "Adios"]}, {updateField: "New Value"})

That’s it for this lesson. If you have any queries feel free to reach out on social media or comment below expect a reply with 30min if I am not asleep­čśé

ManOrInfinity Written by:

Coding, Fitness, Writing are three of my passions. I am a bit complicated in my mind but fairly simpler outside. Sharing my knowledge and learning from others are two of my best qualities. One last thing. I don't like to reveal too much about myself!

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.