0
0
MongoDBquery~5 mins

$nor operator behavior in MongoDB

Choose your learning style9 modes available
Introduction

The $nor operator helps find documents that do not match any of the given conditions. It is like saying "none of these" in a search.

You want to find users who are neither from New York nor from California.
You want to get products that are not cheap and not on sale.
You want to exclude documents that have either a missing field or a specific value.
You want to filter out records that match any of several unwanted conditions.
Syntax
MongoDB
{ $nor: [ { condition1 }, { condition2 }, ... ] }

The $nor operator takes an array of conditions.

It returns documents where none of the conditions are true.

Examples
Finds documents where age is neither less than 18 nor greater than 65.
MongoDB
{ $nor: [ { age: { $lt: 18 } }, { age: { $gt: 65 } } ] }
Finds documents where status is not "A" and qty is not less than 30.
MongoDB
{ $nor: [ { status: "A" }, { qty: { $lt: 30 } } ] }
Sample Program

This query finds documents where status is not "A" and qty is not less than 50. It excludes any document matching either condition.

MongoDB
db.inventory.insertMany([
  { item: "journal", qty: 25, status: "A" },
  { item: "notebook", qty: 50, status: "A" },
  { item: "paper", qty: 100, status: "D" },
  { item: "planner", qty: 75, status: "D" },
  { item: "postcard", qty: 45, status: "A" }
])

// Find items where status is neither "A" nor qty less than 50

const result = db.inventory.find({ $nor: [ { status: "A" }, { qty: { $lt: 50 } } ] }).toArray()

printjson(result)
OutputSuccess
Important Notes

The $nor operator is the opposite of $or. It returns documents that do not satisfy any of the conditions.

If the array is empty, $nor matches all documents.

Summary

$nor finds documents where none of the given conditions are true.

It takes an array of conditions and excludes documents matching any of them.

Useful to filter out unwanted records based on multiple criteria.