$expr का उपयोग
$expr एक query को same document के fields compare करने या aggregation expressions इस्तेमाल करने देता है।
In this page:
Syntax
db.collection_name.find({ $expr: { $gt: ["$field1", "$field2"] } })
$expr
$expr के अंदर आप aggregation-style expressions लिखते हैं जैसे { $gt: ["$spent", "$budget"] }, जो same document की दो fields compare करता है। यह powerful है लेकिन plain field queries जितना effectively indexes इस्तेमाल नहीं कर सकता।
Note:
field-to-field comparisons और computed conditions के लिए $expr इस्तेमाल करें।
उदाहरण: $expr
test> db.budgets.insertMany([{ _id: 1, name: "A", budget: 100, spent: 120 }, { _id: 2, name: "B", budget: 100, spent: 40 }, { _id: 3, name: "C", budget: 50, spent: 50 }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.budgets.find({ $expr: { $gt: ["$spent", "$budget"] } }, { name: 1, _id: 0 })
[ { name: 'A' } ]
test> db.budgets.find({ $expr: { $gte: [{ $multiply: ["$spent", 2] }, 100] } }, { name: 1, _id: 0 })
[ { name: 'A' }, { name: 'C' } ]
⚠️ 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. #}
आम गलतियां
- field references के लिए $ prefix भूल जाना
- यह उम्मीद करना कि indexes हमेशा मदद करेंगे
- query और aggregation syntax mix करना
चैप्टर सारांश
- $expr aggregation expressions इस्तेमाल करता है
- Fields "$field" की तरह reference होती हैं
- एक document में fields compare करता है
- शायद indexes उतने अच्छे इस्तेमाल न करे
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: