دوره‌ها / MongoDB / Text Indexes (Text Indexes)

Text Indexes (Text Indexes)

15 دقیقه Article

Text Indexes: جستجوی متنی 🔤

Text Index برای جستجوی full-text در documents استفاده می‌شود. این نوع index به شما امکان می‌دهد در متن‌ها جستجو کنید.

ساخت Text Index:

// Text index روی یک فیلد
db.articles.createIndex({ title: "text" })

// Text index روی چند فیلد
db.articles.createIndex({ title: "text", content: "text" })

// فقط یک text index در هر collection
// اگر می‌خواهید چند فیلد داشته باشید، همه را در یک index قرار دهید

جستجوی متنی:

// جستجوی ساده
db.articles.find({ $text: { $search: "MongoDB" } })

// جستجوی چند کلمه (OR)
db.articles.find({ $text: { $search: "MongoDB tutorial" } })

// جستجو با score (مرتب‌سازی بر اساس relevance)
db.articles.find(
  { $text: { $search: "MongoDB" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })

// جستجو با language
db.articles.createIndex({ content: "text" }, { default_language: "english" })

محدودیت‌ها:

  • فقط یک text index در هر collection
  • نمی‌توانید text index را در compound index استفاده کنید (مگر اینکه همه فیلدها text باشند)
  • Case-insensitive است
💡 نکته: Text Index برای جستجوی متنی در مقالات، پست‌ها، نظرات و محتوای متنی عالی است. برای جستجوی پیشرفته‌تر، می‌توانید از MongoDB Atlas Search استفاده کنید.
✅ یاد گرفتید: Text Indexes برای جستجوی متنی و full-text search در documents استفاده می‌شوند!

تمرین‌های عملی

برای تثبیت یادگیری این درس تمرین‌های زیر را حل کنید

تمرین: Text Index Medium
سوال تمرین

🎯 تمرین: ساخت Text Index

یک text index بسازید و جستجو کنید.

پاسخ تمرین
JAVASCRIPT
// Text Index
db.articles.createIndex({ title: "text", content: "text" })

// جستجو
db.articles.find({ $text: { $search: "mongodb tutorial" } })

// با score
db.articles.find(
    { $text: { $search: "mongodb" } },
    { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })

آماده رفتن به درس بعدی هستید؟

این درس را به پایان رساندید و می‌توانید به درس بعدی بروید.