MongoDB-তে $or অপারেটর ব্যবহার করে ফিল্ড থাকার শর্তে কন্ডিশন প্রয়োগ করা
যদি কোনো ফিল্ড থাকলে শর্ত প্রয়োগ করতে চান, কিন্তু ফিল্ড না থাকলেও ডকুমেন্ট রিটার্ন করতে চান, তবে $or অপারেটর ব্যবহার করুন।
ধাপ ১: ডকুমেন্টসহ কালেকশন তৈরি করুন
> db.applyConditionDemo.insertOne({"StudentName":"Larry","StudentAge":21,"StudentMarks":45});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80b78623186894665ae36") }
> db.applyConditionDemo.insertOne({"StudentName":"Sam","StudentAge":23,"StudentMarks":55});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80b87623186894665ae37") }
> db.applyConditionDemo.insertOne({"StudentName":"David","StudentAge":21,"StudentMarks":65});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80b95623186894665ae38") }
> db.applyConditionDemo.insertOne({"StudentName":"Carol","StudentAge":24,"StudentMarks":78});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80ba3623186894665ae39") }
> db.applyConditionDemo.insertOne({"StudentName":"Chris","StudentAge":21,"StudentMarks":88});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80bae623186894665ae3a") }
> db.applyConditionDemo.insertOne({"StudentName":"Robert","StudentMarks":98});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80c3d623186894665ae3b") }
লক্ষ্য করুন: Robert-এর ডকুমেন্টে StudentAge ফিল্ডটি নেই।
ধাপ ২: সব ডকুমেন্ট প্রদর্শন করুন
> db.applyConditionDemo.find().pretty();
আউটপুট:
{
"_id" : ObjectId("5cb80b78623186894665ae36"),
"StudentName" : "Larry",
"StudentAge" : 21,
"StudentMarks" : 45
}
{
"_id" : ObjectId("5cb80b87623186894665ae37"),
"StudentName" : "Sam",
"StudentAge" : 23,
"StudentMarks" : 55
}
{
"_id" : ObjectId("5cb80b95623186894665ae38"),
"StudentName" : "David",
"StudentAge" : 21,
"StudentMarks" : 65
}
{
"_id" : ObjectId("5cb80ba3623186894665ae39"),
"StudentName" : "Carol",
"StudentAge" : 24,
"StudentMarks" : 78
}
{
"_id" : ObjectId("5cb80bae623186894665ae3a"),
"StudentName" : "Chris",
"StudentAge" : 21,
"StudentMarks" : 88
}
{
"_id" : ObjectId("5cb80c3d623186894665ae3b"),
"StudentName" : "Robert",
"StudentMarks" : 98
}
ধাপ ৩: ফিল্ড থাকার শর্তে কন্ডিশন প্রয়োগ করুন
শর্ত: StudentAge ফিল্ড না থাকা ডকুমেন্টগুলো + StudentAge: 21 হয়ে থাকা ডকুমেন্টগুলো রিটার্ন করুন।
> db.applyConditionDemo.find({ $or: [ { StudentAge: { $exists:false } }, { StudentAge:21 } ] }).pretty();
ফলাফল:
{
"_id" : ObjectId("5cb80b78623186894665ae36"),
"StudentName" : "Larry",
"StudentAge" : 21,
"StudentMarks" : 45
}
{
"_id" : ObjectId("5cb80b95623186894665ae38"),
"StudentName" : "David",
"StudentAge" : 21,
"StudentMarks" : 65
}
{
"_id" : ObjectId("5cb80bae623186894665ae3a"),
"StudentName" : "Chris",
"StudentAge" : 21,
"StudentMarks" : 88
}
{
"_id" : ObjectId("5cb80c3d623186894665ae3b"),
"StudentName" : "Robert",
"StudentMarks" : 98
}
ব্যাখ্যা: $or অপারেটর দুটি শর্তের যেকোনো একটিই সত্য হলে ডকুমেন্ট রিটার্ন করে। প্রথম শর্ত StudentAge: {$exists:false} - Robert-এর ডকুমেন্টটি মেলে (কারণ StudentAge ফিল্ড নেই)। দ্বিতীয় শর্ত StudentAge: 21 - Larry, David, Chris-এর ডকুমেন্টগুলো মেলে।