← Back to MongoDB Course | Chapter 6: Query Operators | Lesson 2 of 7

Logical Operators ($and $or $not $nor) की जानकारी

Logical operators कई conditions को एक query में combine करते हैं।
Syntax
javascript
{ $and: [condition1, condition2] }
{ $or: [condition1, condition2] }
{ field: { $not: { $gt: value } } }
{ $nor: [condition1, condition2] }

Logical Operators ($and $or $not $nor)

$and को सारी conditions चाहिए, $or को कम से कम एक चाहिए, $nor को कोई नहीं चाहिए, और $not एक single operator expression invert करता है।

Top-level conditions implicitly ANDed होती हैं, इसलिए $and मुख्य रूप से तब चाहिए जब same field दो बार appear हो। सिर्फ readability के लिए सबसे selective conditions पहले रखें; planner reorder करता है।

Note: $or clauses अलग indexes इस्तेमाल कर सकते हैं, इसलिए हर branch index करें।

उदाहरण: Logical operators ($and $or $not $nor)

bash
test> db.users.insertMany([
...   { _id: 1, name: "Ada", age: 36, city: "London" }, { _id: 2, name: "Bob", age: 25, city: "Oslo" },
...   { _id: 3, name: "Cy", age: 41, city: "Oslo" }
... ])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.users.find({ $or: [{ city: "London" }, { age: { $gt: 40 } }] }, { name: 1, _id: 0 })
[ { name: 'Ada' }, { name: 'Cy' } ]
test> db.users.find({ $and: [{ age: { $gt: 20 } }, { age: { $lt: 40 } }] }, { name: 1, _id: 0 })
[ { name: 'Ada' }, { name: 'Bob' } ]
test> db.users.find({ age: { $not: { $gt: 30 } } }, { name: 1, _id: 0 })
[ { name: 'Bob' } ]
test> db.users.find({ $nor: [{ city: "Oslo" }, { age: { $lt: 30 } }] }, { name: 1, _id: 0 })
[ { name: 'Ada' } ]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक object में एक key repeat करना और एक condition खोना
  2. एक plain value पर $not इस्तेमाल करना
  3. यह भूल जाना कि $or को एक array चाहिए
चैप्टर सारांश
  • $and सब, $or कोई भी, $nor कोई नहीं
  • $not एक operator expression negate करता है
  • Top-level fields ANDed होते हैं
  • $or को conditions का एक array चाहिए
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.