Karşılaştırma Sorgu Operatörleri

Operatörler ve Açıklamaları

  • $eq (Eşittir): Belirtilen değere tam olarak eşit olan değerleri bulur.

    Kullanım Senaryoları:

    • Tam eşleşme gerektiren aramalar
    • Dizi içindeki belirli değerleri kontrol etme
    • Çoklu alan eşitliği kontrolü
    // Simple equality check
    filter := bson.D{{"age", bson.D{{"$eq", 25}}}}
    
    // Check for specific values in an array
    filter := bson.D{{"tags", bson.D{{"$eq", "mongodb"}}}}
    
    // Multiple field equality check
    filter := bson.D{
        {"$and", bson.A{
            bson.D{{"name", bson.D{{"$eq", "John"}}}},
            bson.D{{"age", bson.D{{"$eq", 30}}}},
        }},
    }
  • $gt (Büyüktür): Belirtilen değerden büyük olan değerleri bulur.

    Kullanım Senaryoları:

    • Maksimum değer kontrolleri
    • Fiyat üst limiti kontrolü
    • Tarih bazlı filtreleme
    // Maximum value check
    filter := bson.D{{"price", bson.D{{"$lt", 1000}}}}
    
    // Date-based filtering
    filter := bson.D{{"createdAt", bson.D{{"$lt", time.Now()}}}}
    
    // Complex price check
    filter := bson.D{
        {"$and", bson.A{
            bson.D{{"price", bson.D{{"$gt", 100}}}},
            bson.D{{"price", bson.D{{"$lt", 200}}}},
        }},
    }
  • $in (İçinde): Belirtilen değerler listesinden herhangi biriyle eşleşen değerleri bulur.

    Kullanım Senaryoları:

    • Çoklu kategori filtreleme
    • Durum kontrolü
    • ID listesi ile filtreleme
  • Çoklu kategori filtreleme
  • Durum kontrolü
  • ID listesi ile filtreleme
// Category filtering
filter := bson.D{{"category", bson.D{{"$in", []string{"electronics", "clothing", "books"}}}}}

// Status check
filter := bson.D{{"status", bson.D{{"$in", []string{"active", "pending"}}}}}

// Filtering with ID list
filter := bson.D{{"_id", bson.D{{"$in", []primitive.ObjectID{id1, id2, id3}}}}}
  • $lt (Küçüktür): Belirtilen değerden küçük olan değerleri bulur.

    Kullanım Senaryoları:

    • Maksimum değer kontrolleri
    • Fiyat aralığı filtreleme
    • Tarih bazlı filtreleme
    // Maximum value check
    filter := bson.D{{"price", bson.D{{"$lt", 100}}}}
    
    // Date-based filtering
    filter := bson.D{{"createdAt", bson.D{{"$lt", time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)}}}}
    
    // Complex price check
    filter := bson.D{
        {"$and", bson.A{
            bson.D{{"price", bson.D{{"$gt", 100}}}},
            bson.D{{"price", bson.D{{"$lt", 200}}}},
        }},
    }
  • $lte (Küçük Eşittir): Belirtilen değerden küçük veya eşit olan değerleri bulur.

    Kullanım Senaryoları:

    • Maksimum değer dahil kontrolleri
    • Fiyat aralığı filtreleme
    • Tarih bazlı filtreleme
    // Maximum value inclusive check
    filter := bson.D{{"price", bson.D{{"$lte", 100}}}}
    
    // Date-based filtering
    filter := bson.D{{"createdAt", bson.D{{"$lte", time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)}}}}
    
    // Complex price check
    filter := bson.D{
        {"$and", bson.A{
            bson.D{{"price", bson.D{{"$gte", 100}}}},
            bson.D{{"price", bson.D{{"$lte", 200}}}},
        }},
    }
  • $ne (Eşit Değildir): Belirtilen değere eşit olmayan tüm değerleri bulur.

    Kullanım Senaryoları:

    • Değer hariç tutma
    • Durum filtreleme
    • Kategori hariç tutma
    // Value exclusion
    filter := bson.D{{"status", bson.D{{"$ne", "deleted"}}}}
    
    // Status filtering
    filter := bson.D{{"role", bson.D{{"$ne", "admin"}}}}
    
    // Complex exclusion
    filter := bson.D{
        {"$and", bson.A{
            bson.D{{"status", bson.D{{"$ne", "deleted"}}}},
            bson.D{{"role", bson.D{{"$ne", "guest"}}}},
        }},
    }
  • $nin (İçinde Değildir): Belirtilen değerler listesinde olmayan değerleri bulur.

    Kullanım Senaryoları:

    • Çoklu değer hariç tutma
    • Durum filtreleme
    • Kategori hariç tutma
    // Multiple value exclusion
    filter := bson.D{{"status", bson.D{{"$nin", []string{"deleted", "inactive"}}}}}
    
    // Status filtering
    filter := bson.D{{"role", bson.D{{"$nin", []string{"admin", "moderator"}}}}}
    
    // Complex exclusion
    filter := bson.D{
        {"$and", bson.A{
            bson.D{{"status", bson.D{{"$nin", []string{"deleted", "inactive"}}}}},
            bson.D{{"role", bson.D{{"$nin", []string{"guest", "banned"}}}}},
        }},
    }
  • Mantıksal Sorgu Operatörleri

    Operatörler ve Açıklamaları

    • $and : Tüm koşulların aynı anda sağlanması gereken sorgular için kullanılır.

      Kullanım Senaryoları:

      • Karmaşık filtreleme koşulları
      • Çoklu alan doğrulaması
      • İç içe koşullar
      // Basic AND usage
      filter := bson.D{{"$and", bson.A{
          bson.D{{"age", bson.D{{"$gt", 18}}}},
          bson.D{{"status", "active"}},
      }}}
      
      // Multiple condition check
      filter := bson.D{{"$and", bson.A{
          bson.D{{"price", bson.D{{"$gt", 100}}}},
          bson.D{{"stock", bson.D{{"$gt", 0}}}},
          bson.D{{"category", "electronics"}},
      }}}
      
      // Nested AND usage
      filter := bson.D{{"$and", bson.A{
          bson.D{{"$and", bson.A{
              bson.D{{"age", bson.D{{"$gt", 18}}}},
              bson.D{{"age", bson.D{{"$lt", 65}}}},
          }}},
          bson.D{{"status", "active"}},
      }}}
    • $or : Koşullardan herhangi birinin sağlanması yeterli olan sorgular için kullanılır.

      Kullanım Senaryoları:

      • Alternatif koşullar
      • Çoklu durum kontrolü
      • Esnek arama kriterleri
      // Basic OR usage
      filter := bson.D{{"$or", bson.A{
          bson.D{{"status", "active"}},
          bson.D{{"status", "pending"}},
      }}}
      
      // Complex OR conditions
      filter := bson.D{{"$or", bson.A{
          bson.D{{"age", bson.D{{"$lt", 18}}}},
          bson.D{{"age", bson.D{{"$gt", 65}}}},
          bson.D{{"status", "retired"}},
      }}}
      
      // AND and OR combination
      filter := bson.D{{"$and", bson.A{
          bson.D{{"category", "electronics"}},
          bson.D{{"$or", bson.A{
              bson.D{{"price", bson.D{{"$lt", 100}}}},
              bson.D{{"discount", bson.D{{"$gt", 20}}}},
          }}},
      }}}
    • $not : Sorgu sonucunu tersine çeviren operatördür.

      Kullanım Senaryoları:

      • Koşulların tersini alma
      • Hariç tutma işlemleri
      • Negatif filtreleme
      // Basic NOT usage
      filter := bson.D{{"age", bson.D{{"$not", bson.D{{"$lt", 18}}}}}}
      
      // Complex NOT condition
      filter := bson.D{{"$not", bson.D{{"$or", bson.A{
          bson.D{{"status", "deleted"}},
          bson.D{{"status", "inactive"}},
      }}}}}
      
      // NOT with regex
      filter := bson.D{{"name", bson.D{{"$not", bson.D{{"$regex", "^test"}}}}}}
    • $nor : Hiçbir koşulun sağlanmaması gereken sorgular için kullanılır.

      Kullanım Senaryoları:

      • Hariç tutma listesi
      • Negatif filtreleme
      • Çoklu koşul dışlama
      // Basic NOR usage
      filter := bson.D{{"$nor", bson.A{
          bson.D{{"status", "deleted"}},
          bson.D{{"status", "inactive"}},
      }}}
      
      // Complex NOR conditions
      filter := bson.D{{"$nor", bson.A{
          bson.D{{"age", bson.D{{"$lt", 18}}}},
          bson.D{{"status", "inactive"}},
          bson.D{{"category", "restricted"}},
      }}}
      
      // NOR with other operators
      filter := bson.D{{"$nor", bson.A{
          bson.D{{"price", bson.D{{"$gt", 1000}}}},
          bson.D{{"stock", bson.D{{"$lt", 5}}}},
      }}}

    Eleman Sorgu Operatörleri

    Operatörler ve Açıklamaları

    • $exists : Belirtilen alanın belgede var olup olmadığını kontrol eder.

      Kullanım Senaryoları:

      • Zorunlu alan kontrolü
      • Eksik veri tespiti
      • Şema doğrulama
      // Basic existence check
      filter := bson.D{{"email", bson.D{{"$exists", true}}}}
      
      // Missing field check
      filter := bson.D{{"phone", bson.D{{"$exists", false}}}}
      
      // Multiple field check
      filter := bson.D{{"$and", bson.A{
          bson.D{{"name", bson.D{{"$exists", true}}}},
          bson.D{{"age", bson.D{{"$exists", true}}}},
          bson.D{{"email", bson.D{{"$exists", true}}}},
      }}}
    • $type : Alanın veri tipini kontrol eder.

      Kullanım Senaryoları:

      • Veri tipi doğrulama
      • Tip dönüşümü öncesi kontrol
      • Şema tutarlılığı kontrolü
      // Numerical type check
      filter := bson.D{{"age", bson.D{{"$type", "number"}}}}
      
      // Array type check
      filter := bson.D{{"tags", bson.D{{"$type", "array"}}}}
      
      // Multiple type check
      filter := bson.D{{"$or", bson.A{
          bson.D{{"price", bson.D{{"$type", "number"}}}},
          bson.D{{"price", bson.D{{"$type", "string"}}}},
      }}}
      
      // Date type check
      filter := bson.D{{"createdAt", bson.D{{"$type", "date"}}}}

    Değerlendirme Sorgu Operatörleri

    Operatörler ve Açıklamaları

    • $expr : Sorgu içinde ifadeler kullanmayı sağlar.

      Kullanım Senaryoları:

      • Alanlar arası karşılaştırma
      • Matematiksel işlemler
      • Karmaşık koşullar
      // Field comparison
      filter := bson.D{{"$expr", bson.D{{"$gt", []string{"$price", "$cost"}}}}}
      
      // Mathematical operation
      filter := bson.D{{"$expr", bson.D{{"$gt", []interface{}{
          bson.D{{"$multiply", []interface{}{"$quantity", "$price"}}},
          1000,
      }}}}}
      
      // Complex condition
      filter := bson.D{{"$expr", bson.D{{"$and", []interface{}{
          bson.D{{"$gt", []string{"$price", "$cost"}}},
          bson.D{{"$gt", []interface{}{"$stock", 0}}},
      }}}}}
    • $jsonSchema : JSON şemasına göre doğrulama yapar.

      Kullanım Senaryoları:

      • Şema doğrulama
      • Veri yapısı kontrolü
      • Alan kısıtlamaları
      // Basic schema validation
      filter := bson.D{{"$jsonSchema", bson.D{
          {"bsonType", "object"},
          {"required", []string{"name", "age", "email"}},
          {"properties", bson.D{
              {"name", bson.D{{"bsonType", "string"}}},
              {"age", bson.D{{"bsonType", "int"}}},
              {"email", bson.D{{"bsonType", "string"}}},
          }},
      }}}
      
      // Complex schema validation
      filter := bson.D{{"$jsonSchema", bson.D{
          {"bsonType", "object"},
          {"required", []string{"name", "scores"}},
          {"properties", bson.D{
              {"name", bson.D{{"bsonType", "string"}}},
              {"scores", bson.D{
                  {"bsonType", "array"},
                  {"items", bson.D{{"bsonType", "int"}}},
                  {"minItems", 1},
              }},
          }},
      }}}
    • $mod : Modül işlemi yapar.

      Kullanım Senaryoları:

      • Çift/tek sayı kontrolü
      • Belirli aralıklarla filtreleme
      • Sayısal gruplama
      // Even number check
      filter := bson.D{{"number", bson.D{{"$mod", []int{2, 0}}}}}
      
      // Multiples of 5
      filter := bson.D{{"value", bson.D{{"$mod", []int{5, 0}}}}}
      
      // Complex mod operation
      filter := bson.D{{"$expr", bson.D{{"$eq", []interface{}{
          bson.D{{"$mod", []interface{}{"$number", 3}}},
          0,
      }}}}}
    • $regex : Düzenli ifade ile eşleştirme yapar.

      Kullanım Senaryoları:

      • Metin arama
      • Desen eşleştirme
      • Kısmi eşleşme
      // Basic text search
      filter := bson.D{{"name", bson.D{{"$regex", "john", "i"}}}}
      
      // Complex pattern matching
      filter := bson.D{{"email", bson.D{{"$regex", "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"}}}}
      
      // Multiple condition with regex
      filter := bson.D{{"$and", bson.A{
          bson.D{{"name", bson.D{{"$regex", "^A"}}}},
          bson.D{{"email", bson.D{{"$regex", "@gmail\\.com$"}}}},
      }}}
    • $where : JavaScript ifadeleri kullanmayı sağlar.

      Kullanım Senaryoları:

      • Karmaşık hesaplamalar
      • JavaScript fonksiyonları
      • Özel filtreleme mantığı
      // Basic JavaScript expression
      filter := bson.D{{"$where", "this.age > 18"}}
      
      // Complex JavaScript function
      filter := bson.D{{"$where", "function() { return this.price * this.quantity > 1000 }"}}
      
      // Date comparison
      filter := bson.D{{"$where", "this.createdAt > new Date('2024-01-01')"}}

    Dizi Sorgu Operatörleri

    Operatörler ve Açıklamaları

    • $all : Belirtilen tüm öğeleri içeren dizileri bulur.

      Kullanım Senaryoları:

      • Etiket kontrolü
      • Yetenek eşleştirme
      • Çoklu özellik kontrolü
      // Basic tag check
      filter := bson.D{{"tags", bson.D{{"$all", []string{"mongodb", "go"}}}}}
      
      // Skill matching
      filter := bson.D{{"skills", bson.D{{"$all", []string{"javascript", "react", "nodejs"}}}}}
      
      // Complex array check
      filter := bson.D{{"$and", bson.A{
          bson.D{{"tags", bson.D{{"$all", []string{"backend", "database"}}}}},
          bson.D{{"languages", bson.D{{"$all", []string{"go", "python"}}}}},
      }}}
    • $elemMatch : Dizi içindeki öğelerin belirli koşulları sağlaması gereken belgeleri bulur.

      Kullanım Senaryoları:

      • Karmaşık dizi filtreleme
      • Çoklu koşul eşleştirme
      • İç içe dizi kontrolü
      // Basic elemMatch usage
      filter := bson.D{{"scores", bson.D{{"$elemMatch", bson.D{
          {"subject", "mathematics"},
          {"score", bson.D{{"$gt", 90}}},
      }}}}}
      
      // Multiple condition elemMatch
      filter := bson.D{{"comments", bson.D{{"$elemMatch", bson.D{
          {"author", "John"},
          {"rating", bson.D{{"$gt", 4}}},
          {"date", bson.D{{"$gt", time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)}}},
      }}}}}
      
      // Nested array check
      filter := bson.D{{"orders", bson.D{{"$elemMatch", bson.D{
          {"items", bson.D{{"$elemMatch", bson.D{
              {"product", "laptop"},
              {"quantity", bson.D{{"$gt", 1}}},
          }}}},
          {"status", "completed"},
      }}}}}
    • $size : Belirli boyuttaki dizileri bulur.

      Kullanım Senaryoları:

      • Dizi uzunluğu kontrolü
      • Boş dizi kontrolü
      • Minimum/maksimum uzunluk kontrolü
      // Specific length check
      filter := bson.D{{"tags", bson.D{{"$size", 3}}}}
      
      // Empty array check
      filter := bson.D{{"comments", bson.D{{"$size", 0}}}}
      
      // Complex length check
      filter := bson.D{{"$and", bson.A{
          bson.D{{"$expr", bson.D{{"$gt", []interface{}{bson.D{{"$size", "$items"}}, 0}}}}},
          bson.D{{"$expr", bson.D{{"$lte", []interface{}{bson.D{{"$size", "$items"}}, 10}}}}},
      }}}

    Alan Güncelleme Operatörleri

    Operatörler ve Açıklamaları

    • $set : Belge alanlarını günceller.

      Kullanım Senaryoları:

      • Tek alan güncelleme
      • Çoklu alan güncelleme
      • İç içe alan güncelleme
      // Single field update
      update := bson.D{{"$set", bson.D{{"status", "active"}}}}
      
      // Multiple field update
      update := bson.D{{"$set", bson.D{
          {"status", "updated"},
          {"lastModified", time.Now()},
          {"version", 2},
      }}}
      
      // Nested field update
      update := bson.D{{"$set", bson.D{
          {"profile.name", "John Doe"},
          {"profile.email", "john@example.com"},
          {"settings.notifications", true},
      }}}
    • $inc : Sayısal değerleri artırır/azaltır.

      Kullanım Senaryoları:

      • Sayaç artırma/azaltma
      • Stok güncelleme
      • Puan hesaplama
      // Counter increment
      update := bson.D{{"$inc", bson.D{{"viewCount", 1}}}}
      
      // Multiple counter update
      update := bson.D{{"$inc", bson.D{
          {"stock", -1},
          {"soldCount", 1},
          {"totalRevenue", 99.99},
      }}}
      
      // Decrement with negative value
      update := bson.D{{"$inc", bson.D{{"balance", -50}}}}
    • $mul : Sayısal değerleri çarpar.

      Kullanım Senaryoları:

      • Fiyat güncelleme
      • İndirim uygulama
      • Ölçek değiştirme
      // Price update
      update := bson.D{{"$mul", bson.D{{"price", 1.1}}}} // %10 increase
      
      // Discount application
      update := bson.D{{"$mul", bson.D{{"price", 0.8}}}} // %20 discount
      
      // Multiple field multiplication
      update := bson.D{{"$mul", bson.D{
          {"width", 2.54},  
          {"height", 2.54},
          {"depth", 2.54},
      }}}
    • $rename : Alan adlarını değiştirir.

      Kullanım Senaryoları:

      • Alan adı değiştirme
      • Şema güncelleme
      • İç içe alan yeniden adlandırma
      // Single field rename
      update := bson.D{{"$rename", bson.D{{"oldName", "newName"}}}}
      
      // Multiple field rename
      update := bson.D{{"$rename", bson.D{
          {"firstName", "name"},
          {"lastName", "surname"},
          {"emailAddress", "email"},
      }}}
      
      // Nested field rename
      update := bson.D{{"$rename", bson.D{
          {"user.profile.name", "user.profile.fullName"},
          {"user.settings.preferences", "user.settings.options"},
      }}}
    • $unset : Alanları siler.

      Kullanım Senaryoları:

      • Tek alan silme
      • Çoklu alan silme
      • İç içe alan silme
      // Single field deletion
      update := bson.D{{"$unset", bson.D{{"temporaryField", ""}}}}
      
      // Multiple field deletion
      update := bson.D{{"$unset", bson.D{
          {"oldField1", ""},
          {"oldField2", ""},
          {"deprecatedField", ""},
      }}}
      
      // Nested field deletion
      update := bson.D{{"$unset", bson.D{
          {"user.tempData", ""},
          {"user.oldSettings", ""},
      }}}

    Dizi Güncelleme Operatörleri

    Operatörler ve Açıklamaları

    • $ : Sorgu koşuluyla eşleşen dizideki ilk öğeyi günceller.

      Kullanım Senaryoları:

      • İlk eşleşen öğeyi seçme
      • Koşullu dizi filtreleme
      • Tekil öğe filtreleme
      // Select first matching element
      filter := bson.D{{"scores", bson.D{{"$gt", 90}}}}
      projection := bson.D{{"scores.$", 1}}
      
      // Conditional projection
      filter := bson.D{{"items", bson.D{{"$elemMatch", bson.D{{"status", "active"}}}}}}
      projection := bson.D{{"items.$", 1}}
      
      // Nested array projection
      filter := bson.D{{"orders.items", bson.D{{"$elemMatch", bson.D{{"product", "laptop"}}}}}}
      projection := bson.D{{"orders.$.items.$", 1}}
    • $[] : Tüm eşleşen öğeleri günceller.

      Kullanım Senaryoları:

      • Toplu dizi güncelleme
      • Tüm öğeleri değiştirme
      • Çoklu dizi işlemi
      // Update all elements
      update := bson.D{{"$set", bson.D{{"scores.$[].status", "reviewed"}}}}
      
      // Multiple array update
      update := bson.D{{"$mul", bson.D{{"prices.$[]", 1.1}}}} // Tüm fiyatları %10 artır
      
      // Nested array update
      update := bson.D{{"$set", bson.D{{"orders.$[].items.$[].discount", 0.2}}}}
    • $[] : Belirli koşullara göre öğeleri günceller.

      Kullanım Senaryoları:

      • Filtreli dizi güncelleme
      • Koşullu toplu güncelleme
      • Özel dizi filtreleme
      // Filtered update
      filter := bson.D{{"items", bson.D{{"$elemMatch", bson.D{{"price", bson.D{{"$gt", 100}}}}}}}}
      update := bson.D{{"$set", bson.D{{"items.$[elem].discount", 0.2}}}}
      opts := options.Update().SetArrayFilters(options.ArrayFilters{
          Filters: []interface{}{bson.D{{"elem.price", bson.D{{"$gt", 100}}}}},
      })
      
      // Multiple conditional update
      filter := bson.D{{"orders", bson.D{{"$elemMatch", bson.D{{"status", "pending"}}}}}}
      update := bson.D{{"$set", bson.D{{"orders.$[order].status", "processing"}}}}
      opts := options.Update().SetArrayFilters(options.ArrayFilters{
          Filters: []interface{}{bson.D{{"order.status", "pending"}}},
      })
    • $addToSet : Tekrarsız öğe ekler.

      Kullanım Senaryoları:

      • Benzersiz değer ekleme
      • Etiket yönetimi
      • Çoklu öğe ekleme
      // Single element addition
      update := bson.D{{"$addToSet", bson.D{{"tags", "new"}}}}
      
      // Multiple element addition
      update := bson.D{{"$addToSet", bson.D{{"tags", bson.D{
          {"$each", []string{"tag1", "tag2", "tag3"}},
      }}}}}
      
      // Complex element addition
      update := bson.D{{"$addToSet", bson.D{{"categories", bson.D{
          {"$each", []string{"electronics", "gadgets"}},
          {"$slice", 5}, // Maximum 5 elements
      }}}}}
    • $pop : İlk veya son öğeyi kaldırır.

      Kullanım Senaryoları:

      • Son öğeyi kaldırma
      • İlk öğeyi kaldırma
      • Kuyruk işlemleri
      // Remove last element
      update := bson.D{{"$pop", bson.D{{"items", 1}}}}
      
      // Remove first element
      update := bson.D{{"$pop", bson.D{{"queue", -1}}}}
      
      // Multiple array operation
      update := bson.D{{"$pop", bson.D{
          {"items", 1},    // Remove last element
          {"queue", -1},   // Remove first element
      }}}
    • $pull : Koşula uyan öğeleri kaldırır.

      Kullanım Senaryoları:

      • Değere göre kaldırma
      • Koşullu kaldırma
      • Çoklu öğe kaldırma
      // Remove by value
      update := bson.D{{"$pull", bson.D{{"tags", "old"}}}}
      
      // Conditional removal
      update := bson.D{{"$pull", bson.D{{"items", bson.D{
          {"price", bson.D{{"$lt", 10}}},
      }}}}}
      
      // Multiple conditional removal
      update := bson.D{{"$pull", bson.D{{"comments", bson.D{
          {"author", "John"},
          {"rating", bson.D{{"$lt", 3}}},
      }}}}}
    • $push : Yeni öğe ekler.

      Kullanım Senaryoları:

      • Tek öğe ekleme
      • Çoklu öğe ekleme
      • Dizi sınırlama
      // Single element addition
      update := bson.D{{"$push", bson.D{{"items", "new item"}}}}
      
      // Multiple element addition
      update := bson.D{{"$push", bson.D{{"items", bson.D{
          {"$each", []string{"item1", "item2", "item3"}},
      }}}}}
      
      // Array limiting with addition
      update := bson.D{{"$push", bson.D{{"recentItems", bson.D{
          {"$each", []string{"item1", "item2"}},
          {"$slice", -5},  // Keep last 5 elements
      }}}}}

    Projeksiyon Operatörleri

    Operatörler ve Açıklamaları

    • $ : Sorgu koşuluyla eşleşen dizideki ilk öğeyi yansıtır.

      Kullanım Senaryoları:

      • İlk eşleşen öğeyi seçme
      • Koşullu dizi filtreleme
      • Tekil öğe filtreleme
      // Select first matching element
      filter := bson.D{{"scores", bson.D{{"$gt", 90}}}}
      projection := bson.D{{"scores.$", 1}}
      
      // Conditional projection
      filter := bson.D{{"items", bson.D{{"$elemMatch", bson.D{{"status", "active"}}}}}}
      projection := bson.D{{"items.$", 1}}
      
      // Nested array projection
      filter := bson.D{{"orders.items", bson.D{{"$elemMatch", bson.D{{"product", "laptop"}}}}}}
      projection := bson.D{{"orders.$.items.$", 1}}
    • $elemMatch : Belirtilen koşulla eşleşen dizideki ilk öğeyi yansıtır.

      Kullanım Senaryoları:

      • Çoklu koşul projeksiyonu
      • Karmaşık dizi filtreleme
      • Özel eşleşme projeksiyonu
      // Multiple condition projection
      projection := bson.D{{"scores", bson.D{{"$elemMatch", bson.D{
          {"subject", "math"},
          {"score", bson.D{{"$gt", 90}}},
      }}}}}
      
      // Complex projection
      projection := bson.D{{"comments", bson.D{{"$elemMatch", bson.D{
          {"author", "John"},
          {"rating", bson.D{{"$gt", 4}}},
          {"date", bson.D{{"$gt", time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)}}},
      }}}}}
    • $meta : Meta verileri yansıtır.

      Kullanım Senaryoları:

      • Metin arama puanı
      • İndeks bilgisi
      • Özel meta veriler
      // Text search score
      filter := bson.D{{"$text", bson.D{{"$search", "mongodb"}}}}
      projection := bson.D{
          {"score", bson.D{{"$meta", "textScore"}}},
          {"title", 1},
      }
      
      // Index information
      projection := bson.D{
          {"_id", 1},
          {"indexInfo", bson.D{{"$meta", "indexKey"}}},
      }
      
      // Complex metadata projection
      projection := bson.D{
          {"title", 1},
          {"description", 1},
          {"searchScore", bson.D{{"$meta", "textScore"}}},
          {"indexDetails", bson.D{{"$meta", "indexKey"}}},
      }
    • $slice : Diziden belirli sayıda öğe yansıtır.

      Kullanım Senaryoları:

      • Belirli sayıda öğe seçme
      • Aralık bazlı seçim
      • Son öğeleri alma
      // Select first 5 elements
      projection := bson.D{{"comments", bson.D{{"$slice", 5}}}}
      
      // Select elements in a range
      projection := bson.D{{"items", bson.D{{"$slice", []int{5, 10}}}}}
      
      // Select last elements
      projection := bson.D{{"recentActivities", bson.D{{"$slice", -5}}}}
      
      // Complex slicing
      projection := bson.D{
          {"comments", bson.D{{"$slice", 5}}},
          {"recentOrders", bson.D{{"$slice", -3}}},
          {"allItems", bson.D{{"$slice", []int{10, 20}}}},
      }

    Çeşitli Sorgu Operatörleri

    Operatörler ve Açıklamaları

    • $rand : Rastgele değer üretir.

      Kullanım Senaryoları:

      • Rastgele belge seçimi
      • Örnekleme
      • Test verisi oluşturma
      // Random document selection
      filter := bson.D{{"$expr", bson.D{{"$gt", []interface{}{"$random", 0.5}}}}}
      
      // Select a specific number of documents
      pipeline := mongo.Pipeline{
          {{"$sample", bson.D{{"size", 10}}}},
      }
      
      // Complex random selection
      filter := bson.D{{"$expr", bson.D{{"$and", []interface{}{
          bson.D{{"$gt", []interface{}{"$random", 0.3}}},
          bson.D{{"$lt", []interface{}{"$random", 0.7}}},
      }}}}}
    • $natural : Doğal sıralama için kullanılır.

      Kullanım Senaryoları:

      • Fiziksel sıralama
      • Depolama sırası
      • Performans optimizasyonu
      // Query with natural ordering
      opts := options.Find().SetHint(bson.D{{"$natural", 1}})
      
      // Reverse natural ordering
      opts := options.Find().SetHint(bson.D{{"$natural", -1}})
      
      // Complex natural ordering
      pipeline := mongo.Pipeline{
          {{"$sort", bson.D{{"$natural", 1}}}},
          {{"$limit", 100}},
      }
    • $comment : Sorguya açıklama ekler.

      Kullanım Senaryoları:

      • Sorgu belgeleme
      • Hata ayıklama
      • Performans izleme
      // Simple comment
      filter := bson.D{{"$comment", "User search query"}} 
      
      // Complex comment
      filter := bson.D{
          {"$and", bson.A{
              bson.D{{"status", "active"}},
              bson.D{{"age", bson.D{{"$gt", 18}}}},
          }},
          {"$comment", "Find active adult users"},
      }
    • $explain : Sorgu planını açıklar.

      Kullanım Senaryoları:

      • Sorgu optimizasyonu
      • Performans analizi
      • İndeks kullanımı kontrolü
      // Query plan explanation
      opts := options.Find().SetExplain(true)
      
      // Detailed explanation
      opts := options.Find().
          SetExplain(true).
          SetVerbosity("executionStats")
      
      // Complex query analysis
      pipeline := mongo.Pipeline{
          {{"$match", bson.D{{"status", "active"}}}},
          {{"$group", bson.D{
              {"_id", "$category"},
              {"count", bson.D{{"$sum", 1}}},
          }}},
      }
      opts := options.Aggregate().SetExplain(true)

    Örnek Kodlar

    Metin Arama ve İndeksleme

    Kullanım Senaryoları:

    • Metin tabanlı arama
    • İçerik indeksleme
    • Tam metin araması
    // Create text index
    indexModel := mongo.IndexModel{
        Keys: bson.D{{"description", "text"}},
    }
    name, err := collection.Indexes().CreateOne(context.TODO(), indexModel)
    
    // Text search example
    filter := bson.D{{"$text", bson.D{{"$search", "search term"}}}}

    Agregasyon Pipeline

    Kullanım Senaryoları:

    • Veri analizi
    • İstatistiksel hesaplamalar
    • Veri dönüşümü
    pipeline := mongo.Pipeline{
        {{"$match", bson.D{{"status", "active"}}}},
        {{"$group", bson.D{
            {"_id", "$category"},
            {"total", bson.D{{"$sum", 1}}},
        }}},
        {{"$sort", bson.D{{"total", -1}}}},
        {{"$limit", 10}},
    }
    cursor, err := collection.Aggregate(context.TODO(), pipeline)

    İşlemler (Transactions)

    Kullanım Senaryoları:

    • Atomik işlemler
    • Veri tutarlılığı
    • Çoklu koleksiyon güncellemeleri
    session, err := client.StartSession()
    if err != nil {
        log.Fatal(err)
    }
    defer session.EndSession(context.TODO())
    
    err = session.StartTransaction()
    if err != nil {
        log.Fatal(err)
    }
    
    // Operations within transaction
    _, err = collection.InsertOne(session, bson.D{{"name", "John"}})
    if err != nil {
        session.AbortTransaction(session)
        log.Fatal(err)
    }
    
    err = session.CommitTransaction(session)
    if err != nil {
        log.Fatal(err)
    }

    Belge Sayma ve Benzersiz Değerler

    Kullanım Senaryoları:

    • İstatistiksel analiz
    • Veri doğrulama
    • Performans optimizasyonu
    // Approximate document count
    count, err := collection.EstimatedDocumentCount(context.TODO())
    
    // Exact document count
    count, err := collection.CountDocuments(context.TODO(), filter)
    
    // Unique values
    results, err := collection.Distinct(context.TODO(), "field", filter)

    ObjectId Dönüşümleri

    Kullanım Senaryoları:

    • ID dönüşümleri
    • Veri doğrulama
    • API entegrasyonları
    // Convert from String to ObjectId
    objectId, err := primitive.ObjectIDFromHex("675d3a322979f406206c8341")
    if err != nil {
        log.Fatal(err)
    }
    
    // Convert from ObjectId to String
    stringID := objectId.Hex()

    CountOptions Yapılandırması

    Kullanım Senaryoları:

    • Gelişmiş sayım işlemleri
    • Performans optimizasyonu
    • Dil bazlı sıralama
    opts := options.Count().
        SetCollation(&options.Collation{Locale: "tr"}).  // Language sorting type
        SetHint(bson.D{{"indexName", 1}}).              // Index to use
        SetLimit(100).                                   // Maximum document count
        SetMaxTime(5 * time.Second).                     // Maximum execution time
        SetSkip(10)                                      // Number of documents to skip
    
    count, err := collection.CountDocuments(context.TODO(), filter, opts)

    Distinct Kullanımı

    Kullanım Senaryoları:

    • Benzersiz değer analizi
    • Kategori listeleme
    • Veri temizleme
    // Get unique values with specific filter
    filter := bson.D{{"title", "Back to the Future"}}
    results, err := collection.Distinct(context.TODO(), "year", filter)
    
    // Get unique values without filter
    results, err := collection.Distinct(context.TODO(), "department", nil)

    Find Options

    Kullanım Senaryoları:

    • Gelişmiş sorgulama
    • Sayfalama
    • Alan seçimi
    // Sorting
    opts := options.Find().SetSort(bson.D{{"enrollment", 1}})  // 1: ascending, -1: descending
    
    // Limit and Skip 
    opts := options.Find().
        SetLimit(2).                    // First 2 documents
        SetSkip(1)                      // Skip first document
    
    // Projection (Determine which fields to return)
    opts := options.Find().SetProjection(bson.D{
        {"course_id", 0},              // 0: exclude, 1: include
        {"enrollment", 0},
    })
    
    // Combined usage
    opts := options.Find().
        SetSort(bson.D{{"enrollment", 1}}).
        SetSkip(1).
        SetLimit(2).
        SetProjection(bson.D{{"title", 1}})

    Metin Arama Özellikleri

    Kullanım Senaryoları:

    • Gelişmiş metin araması
    • Tam ifade araması
    • Metin skorlaması
    // Create text index
    model := mongo.IndexModel{
        Keys: bson.D{{"description", "text"}},
    }
    name, err := collection.Indexes().CreateOne(context.TODO(), model)
    
    // Simple text search
    filter := bson.D{{"$text", bson.D{{"$search", "SERVES fish"}}}}
    
    // Exact phrase search
    filter := bson.D{{"$text", bson.D{{"$search", "\"serves 2\""}}}}
    
    // Search with exclusion
    filter := bson.D{{"$text", bson.D{{"$search", "vegan -tofu"}}}}
    
    // Sorting and scoring text search results 
    filter := bson.D{{"$text", bson.D{{"$search", "vegetarian"}}}}
    sort := bson.D{{"score", bson.D{{"$meta", "textScore"}}}}
    projection := bson.D{
        {"name", 1},
        {"description", 1},
        {"score", bson.D{{"$meta", "textScore"}}},
        {"_id", 0},
    }
    opts := options.Find().SetSort(sort).SetProjection(projection)

    Dizi Güncelleme Detayları

    Kullanım Senaryoları:

    • Belirli dizi öğelerini güncelleme
    • Dizi filtreleri ile güncelleme
    • Toplu dizi güncelleme
    // Update specific array element
    update := bson.D{{"$inc", bson.D{{"sizes.$", -2}}}}
    
    // Update with array filters
    identifier := bson.D{{"hotOptions", bson.D{{"$gt", 100}}}}
    update := bson.D{{"$unset", bson.D{{"styles.$[hotOptions]", ""}}}}
    opts := options.Update().
        SetArrayFilters(options.ArrayFilters{Filters: identifier}).
        SetReturnDocument(options.After)
    
    // Update all array elements
    update := bson.D{{"$mul", bson.D{{"sizes.$[]", 29.57}}}}

    Koleksiyon Oluşturma ve İndeksleme

    Kullanım Senaryoları:

    • Kümelenmiş indeks oluşturma
    • Benzersiz indeks tanımlama
    • Performans optimizasyonu
    // Creating a collection with a clustered index
    cio := bson.D{{"key", bson.D{{"_id", 1}}}, {"unique", true}}
    opts := options.CreateCollection().SetClusteredIndex(cio)
    db.CreateCollection(context.TODO(), "yeniKoleksiyon", opts)
    
    // Creating a unique index
    indexModel := mongo.IndexModel{
        Keys:    bson.D{{"theaterId", -1}},
        Options: options.Index().SetUnique(true),
    }
    name, err := collection.Indexes().CreateOne(context.TODO(), indexModel)