Search for documents that does not contain field value from a given Array in MongoDB

Search for document that does not contain field from a given Array in MongoDB

In some cases you want to find all documents that some field of it are not inside of a given array. To do so we will use the "$nin" operator which takes an array as a value.

Let's say you have a collection named "articles" where you have the following two attributes "name" and "type" and you want to find the documents that their type is not in "snippets" or "articles" to show them to the end user.

Inserting Documents

db.articles.insertMany([
{ type: "articles", name: "artciles 1" },
{ type: "snippets", name: "snippets 1" },
{ type: "issues", name: "issues 1" },
])

Search for documents not in our array

db.articles.find({ type: { $nin: ["snippets", "articles"] }})

Result

{ "_id" : ObjectId("5e3ae4d1dfa432477f1227fd"), "type" : "issues", "name" : "issues 1" }