# Mongo DB Kullanımı

## MongoDB Nedir?

* NoSQL (Not Only SQL) veritabanıdır
* Dünya çapında kullanılan Popüler Veritabanlarından bir tanesidir.
* BSON-JSON formatında çalıştır

### Yararlanılan Kaynaklar

* <https://www.mongodb.com/docs/drivers/csharp/current/>
* <https://learn.microsoft.com/tr-tr/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-7.0&tabs=visual-studio>

## Kurulum

* MongoDB, ATLAS Cloud üzerinde ücretli çalışan bir veritabanıdır. Öğrenme amaçlı Free sürümü AWS ortamında vardır.
* Local bilgisayara MSI.exec ile kurulumu yapılabilir. Ben bu makalede local bilgisayarıma MongoDB kurup denemeleri yaptım.

## &#x20;VisualStudio Console Projesi Oluşturma

* .NetFramework 4.7.2 ConsoleApplication projesi oluşturun
* Install - Package MongoDB.Driver -version 2.20.0 komutunu package managerdan çalıştırıp driver kurun.

## MongoDB IDE

IDE Kullanımı PostgreSQL ve ElasticSearch’e benzemektedir. MongoDB Compass olarak adı geçer.

{% code title="Program.cs" lineNumbers="true" %}

```csharp
using System;
using System.Threading.Tasks;
 
namespace MongoDbArge
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            // https://www.mongodb.com/try/download/community
            // Install - Package MongoDB.Driver -version 2.20.0
            // https://www.mongodb.com/docs/drivers/csharp/current/
            // https://learn.microsoft.com/tr-tr/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-7.0&tabs=visual-studio
 
            var conString = "mongodb://localhost:27017/";
            var res = new object();
            BlogRepository repo = new BlogRepository(conString, "ArkSoftBlogDb", "DevBlog");
 
            // CheckConnection
            res = repo.CheckConnection();
            Console.WriteLine("== CheckConnection ==");
            Console.WriteLine($"IsConnected:{res}");
 
            // DeleteAllBlogs
            res = await repo.DeleteAllBlogs();
 
            // Insert blogs
            await SeedDatas(repo);
 
            // GetAllUsers
            Console.WriteLine();
            Console.WriteLine($"== GetAllBlogs ==");
            var blogs = await repo.GetAllBlogs();
 
            foreach (var item in blogs)
            {
                Console.WriteLine($"{item.Id} | {item.AuthorName} | {item.Title} | {item.Context} | {item.Category}");
            }
 
            // GetBlogsByField
            Console.WriteLine();
            Console.WriteLine($"== C# Blogları (Filtrelenmiş) ==");
            var filteredBlogs = await repo.GetBlogsByField(nameof(BlogItem.Category), "C#");
 
            foreach (var item in filteredBlogs)
            {
                Console.WriteLine($"{item.Id} | {item.AuthorName} | {item.Title} | {item.Context} | {item.Category}");
            }
 
            Console.ReadLine();
        }
 
        private static async Task SeedDatas(BlogRepository repo)
        {
            var bi = new BlogItem()
            {
                AuthorName = "Başak Toprak HİÇDURMAZ",
                Title = "JIRA Temel Kullanımı ve Özellikleri",
                Context = "Bla bla1...",
                Category = "Business"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Burak GÜLER",
                Title = "Detection Method Oluşturma",
                Context = "Bla bla2...",
                Category = "SCCM/WSUS"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Can DOĞU",
                Title = "Windows Servis Projelerinde PipeLine Kullanımı",
                Context = "Bla bla3...",
                Category = "C#"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Direnç ÖNEN",
                Title = "SCCM/WSUS ve Easy2Patch Entegrasyonu",
                Context = "Bla bla4...",
                Category = "E2P"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Hüsamettin ELALMIŞ",
                Title = "Design Patterns",
                Context = "Bla bla5...",
                Category = "C#"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Mustafa ŞEKER",
                Title = "Angular'da HTTP GET/POST Kullanımı",
                Context = "Bla bla6...",
                Category = "Angular"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Orçun TEN",
                Title = "Docker Kullanımı ve Uygulamalı Deployment",
                Context = "Bla bla7...",
                Category = "C#"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Ömer SOYER",
                Title = "File Upload İşlemlerinde Yazılım Tarafında Dikkat Edilmesi Gereken Hususlar",
                Context = "Bla bla8...",
                Category = "C#"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Tunahan ERKEN",
                Title = "FastReport Designerda Rapor Oluşturmak",
                Context = "Bla bla9...",
                Category = "C#"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Uğur SAĞLAM",
                Title = "Selenium Tabanlı Test Automation Uygulaması Yazmak",
                Context = "Bla bla10...",
                Category = "C#"
            };
            await repo.InsertBlog(bi);
 
 
            bi = new BlogItem()
            {
                AuthorName = "Volkan DİNÇER",
                Title = "Test Süreçleri Hakkında Bilmemiz Gerekenler (BlackBox, WhiteBox ve Diğerleri)",
                Context = "Bla bla11...",
                Category = "Test"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Volkan ÖNDER",
                Title = "Angularda Validation İşlemleri",
                Context = "Bla bla12...",
                Category = "Angular"
            };
            await repo.InsertBlog(bi);
 
            bi = new BlogItem()
            {
                AuthorName = "Yusha KURALAY",
                Title = "HTML5'e Giriş - Template Design Edelim I - ",
                Context = "Bla bla13...",
                Category = "HTML5"
            };
            await repo.InsertBlog(bi);
 
        }
    }
}
```

{% endcode %}

{% code title="Repository.cs" lineNumbers="true" %}

```csharp
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Threading.Tasks;
 
namespace MongoDbArge
{
    public class BlogItem
    {
        [BsonId]
        public ObjectId Id { get; set; }
 
        [BsonElement("authorName")]
        public string AuthorName { get; set; }
 
        [BsonElement("title")]
        public string Title { get; set; }
 
        [BsonElement("context")]
        public string Context { get; set; }
 
        [BsonElement("category")]
        public string Category { get; set; }
    }
 
    public class BlogRepository
    {
        // Variables
        private IMongoClient _client;
        private IMongoDatabase _database;
        private IMongoCollection<BlogItem> _BlogsCollection;
 
        // Ctor
        public BlogRepository(string connectionString, string dataBase, string collection)
        {
            _client = new MongoClient(connectionString);
            _database = _client.GetDatabase(dataBase);
            _BlogsCollection = _database.GetCollection<BlogItem>(collection);
        }
 
        // CheckConnection - bağlantı kontrolü yapar
        public bool CheckConnection()
        {
            try
            {
                _database.ListCollections();
            }
            catch
            {
                return false;
            }
 
            return true;
        }
 
        // GetAllBlogs - Tüm blogları getir
        public async Task<List<BlogItem>> GetAllBlogs()
        {
            return await _BlogsCollection.Find(new BsonDocument()).ToListAsync();
        }
 
        // GetBlogsByField - Filtreleme yapar
        public async Task<List<BlogItem>> GetBlogsByField(string fieldName, string fieldValue)
        {
            var filter = Builders<BlogItem>.Filter.Eq(fieldName, fieldValue);
            var result = await _BlogsCollection.Find(filter).ToListAsync();
 
            return result;
        }
 
        // GetBlogs - Pagination yapar
        public async Task<List<BlogItem>> GetBlogs(int startingFrom, int count)
        {
            var result = await _BlogsCollection.Find(new BsonDocument()).Skip(startingFrom).Limit(count).ToListAsync();
 
            return result;
        }
 
        // InsertBlog - Kayıt ekler
        public async Task InsertBlog(BlogItem user)
        {
            await _BlogsCollection.InsertOneAsync(user);
        }
 
 
        // DeleteBlogById - Kayıt siler
        public async Task<bool> DeleteBlogById(ObjectId id)
        {
            var filter = Builders<BlogItem>.Filter.Eq("_id", id);
            var result = await _BlogsCollection.DeleteOneAsync(filter);
            return result.DeletedCount != 0;
        }
 
        // DeleteAllBlogs - Tüm kayıtları siler
        public async Task<long> DeleteAllBlogs()
        {
            var filter = new BsonDocument();
            var result = await _BlogsCollection.DeleteManyAsync(filter);
            return result.DeletedCount;
        }
 
        // UpdateBlog - Kayıt günceller
        public async Task<bool> UpdateBlog(ObjectId id, string fieldName, string value)
        {
            var filter = Builders<BlogItem>.Filter.Eq("_id", id);
            var update = Builders<BlogItem>.Update.Set(fieldName, value);
            var result = await _BlogsCollection.UpdateOneAsync(filter, update);
 
            return result.ModifiedCount != 0;
        }
 
        // CreateIndexOnNameField - Aktif collection üzerinde alan adına göre göre Index oluşturur
        public async Task CreateIndexOnNameField()
        {
            var keys = Builders<BlogItem>.IndexKeys.Ascending(x => x.AuthorName);
            await _BlogsCollection.Indexes.CreateOneAsync(keys);
        }
 
        // CreateIndexOnCollection - İlgili collection üzerinde Index oluşturur
        public async Task CreateIndexOnCollection(IMongoCollection<BsonDocument> collection, string field)
        {
            var keys = Builders<BsonDocument>.IndexKeys.Ascending(field);
            await collection.Indexes.CreateOneAsync(keys);
        }
    }
}
```

{% endcode %}

## Sonuç

* Bu dokumanda MongoDB kullanımını uygulamalı görmüş olduk
* Repository pattern temel düzeyde kullanılmıştır, genişletilebilir.
* AWS sunucuları üzerinde kullanılabilir.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.yazilimciyiz.biz/temmuz-2023/mongo-db-kullanimi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
