How To Get Documents From MongoDB except One: $nin

Last updated on December 28, 2022

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:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

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