If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
So , अभी तक आपने basic concepts , query और conditional operators के बारे में पढ़ा और समझा। हालाँकि पिछले topic में हमें aggregate() Method के बारे में पढ़ा था। और समझा कि Pipeline में कई stages होती हैं।
उन्ही stages में से एक है $match operator stage , और इस topic में हम इसके बारे में details से समझेंगे।
$match एक query stage है जो MongoDB में use किया जाता है , इसका मैं purpose documents को filter करना है जो भी आपकी need और criteria से match करते हैं। इस stage में आप एक "filter expression" provide करते हैं जो आपके documents को select करता है।
ये expression JSON format में होता है , जिसमे आप specify करते हैं कि किस field के लिए क्या condition होगी। इसमें हम other conditional operators like : $and / $or का भी use कर सकते हैं।
{
$match: {
field1 : value1 ,
field2 : value2
}
}$match stage के अंदर almost हर तरह के conditional operators का use कर सकते हैं , जो भी आपकी need हो।
●●●
अब कुछ examples देख लेते हैं ताकि इसे और अच्छे से समझा जा सके।
1. Suppose आपके पास एक "users" collection है जिसमे "age" field है , आप उन users को filter चाहते हैं जिनकी age 25 से ज्यादा और status Active है।
db.users.aggregate([
{
$match: {
age : { $gt: 25 } ,
status : "Active"
}
}
])normally $match stage में assign किया गया conditional object by default $and की तरह work करता है लेकिन आप $or को manually specify कर सकते हैं।
"products" collection है जिसमे name, price और category field है , आप उन products को filter करना चाहते हैं जिनकी category "Electronics" या price 5000 ज्यादा है।
db.products.aggregate([
{
$match: {
$or : [
{ category: "Electronics" },
{ price: { $gt: 5000 } }
]
}
}
])आप $match के साथ $or और $and दोनों operators का use कर सकते हैं।
Suppose आपके पास "employees" collection है जिसमे name, age, और department field है। अब आप उन employees को filter करना चाहते हैं जो या तो "IT" department में है या उनकी age 30 से कम है , लेकिन उनका नाम "John" नहीं है।
db.employees.aggregate([
{
$match: {
$or: [
{ department: "IT" },
{ age: { $lt: 30 } }
],
$and: [
{ name: { $ne: "John" } }
]
}
}
])तो कुछ इस तरह से आप $match का use करते हैं , हालाँकि आप इसे advance level पर need के according use में ले सकते हैं।
●●●