MongoDB

MongoDB nin Operator

The $nin operator in MongoDB is used to select the documents where a value of a specified field is not in a given array.

Let us explore how we can use this operator.

Operator Syntax

The following shows the syntax of the $nin operator:

{ field: { $nin: [ <value1>, <value2> ... <valueN> ] } }

Let us explore how we can use this operator.

Consider the collection with document as shown in the query below:

db.createCollection("posts")
db.posts.insertMany([
    { title: "Post_1", author: "author_1", year: 2022, category: ["cat1", "cat2"] },
    { title: "Post_2", author: "author_2", year: 2022, category: ["cat1", "cat3"] },
    { title: "Post_3", author: "author_3", year: 2022, category: ["cat3", "cat2"] }
])

Select Unmatching Documents Using the $nin Operator

The example query below shows how to use the $nin operator to select documents where the value of the author field is not equal to 1 or 3.

db.posts.find({author: {$nin: ["author_1", "author_3"]}});

The query above should select the documents not matching the specified condition and return the relevant output.

An example is as shown:

{
    "_id" :ObjectId("632bf2014e8dee924a2279ad"),
    "title" : "Post_2",
    "author" : "author_2",
    "year" : 2022.0,
    "category" : [
"cat1",
"cat3"
    ]
}

Select Element Not in a Given Array Using the $nin Operator

We can also use the $nin operator to filter out any documents that do not include a given element in the array.

For example, in the query below, we use the $nin operator to filter out any document that does not contain cat2 in the category array.

db.posts.find({category: {$nin: ["cat2"]}})

As expected, the above query should return any documents that do not contain the specified element in the array.

{
    "_id" :ObjectId("632bf2014e8dee924a2279ad"),
    "title" : "Post_2",
    "author" : "author_2",
    "year" : 2022.0,
    "category" : [
"cat1",
"cat3"
    ]
}

Update Data Using the $nin Operator

We can also use the $nin operator with UpdateOne or UpdateMany() method. An example is as shown below:

db.posts.updateMany({category: {$nin: ["cat2"]}}, {$set: {exclude: true}})

In this case, the query should update the collection with the documents that do not match the specified condition.

Conclusion

In this post, we discussed how we can use the $nin operator in MongoDB to select unmatching documents, selecting documents not in a given array, and etc.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list