Mongo DB Kullanımı
Husamettin Elalmis
Last updated
Husamettin Elalmis
Last updated
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);
}
}
}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);
}
}
}