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😂
Be First to Comment