কম্পিউটার টিউটোরিয়াল

MongoDB-এ $regex অপারেটর ব্যবহার করার পদ্ধতি

MongoDB-এ স্ট্রিং ফিল্ডে রেগুলার এক্সপ্রেশন (Regex) ভিত্তিক প্যাটার্ন ম্যাচিং করতে $regex অপারেটর ব্যবহার করুন। কেস-সেনসিটিভ এবং কেস-ইনসেনসিটিভ দুভাবেই সম্ভব।

সিনট্যাক্স

db.yourCollectionName.find({ yourFieldName: { $regex: yourValue } });

উদাহরণ

বিভিন্ন কেসের নাম সহ ডকুমেন্ট তৈরি করুন:

> db.regularExpressionDemo.insertOne({"UserName": "John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cdffc25bf3115999ed51210") }

> db.regularExpressionDemo.insertOne({"UserName": "JOHN"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cdffc2ebf3115999ed51211") }

> db.regularExpressionDemo.insertOne({"UserName": "john"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cdffc35bf3115999ed51212") }

> db.regularExpressionDemo.insertOne({"UserName": "JoHn"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cdffc3ebf3115999ed51213") }

সকল ডকুমেন্ট দেখুন:

> db.regularExpressionDemo.find();

আউটপুট:

{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }

১. কেস-সেনসিটিভ ম্যাচ: ঠিক "JOHN"

> db.regularExpressionDemo.find({ 'UserName': { $regex: 'JOHN' } });

আউটপুট:

{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }

২. কেস-ইনসেনসিটিভ ম্যাচ: "john", "John", "JOHN", "JoHn" সব

> db.regularExpressionDemo.find({ 'UserName': { $regex: 'JOHN', $options: 'i' } });

আউটপুট:

{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }

ব্যাখ্যা:

  • $regex: 'JOHN' — প্যাটার্ন নির্দিষ্ট করে।
  • $options: 'i' — কেস-ইনসেনসিটিভ (case-insensitive) করে।
  • অন্যান্য অপশন: m (multiline), s (dot matches newline), x (extended regex)।

বিকল্প সিনট্যাক্স (জাভাস্ক্রিপ্ট রেগেক্স):

db.regularExpressionDemo.find({ 'UserName': /JOHN/i });

সতর্কতা: রেগেক্স ইনডেক্স ব্যবহার করে না (prefix regex ^pattern ছাড়া)। বড় ডেটাসেটে $text ইন্ডেক্স বা Atlas Search ব্যবহার করুন।

  1. MongoDB-এ কালেকশন ড্রপ কীভাবে করবেন?

  2. MongoDB-এ 'Not Like' অপারেটর ব্যবহার করার পদ্ধতি ($not + regex)

  3. MongoDB কনসোল ক্লিয়ার করার পদ্ধতি

  4. ম্যাকে VR (ভার্চুয়াল রিয়েলিটি) ব্যবহারের সম্ভাবনা ও পদ্ধতি