using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
 
namespace TodoList.Data.MongoDB
{
    public class MongoDBRepository<T> : IRepository<T> where T : class, new()
    {
        private readonly IMongoCollection<T> _collection;
 
        public MongoDBRepository(IMongoDatabase database)
        {
            _collection = database.GetCollection<T>(typeof(T).Name.ToLower());
        }
 
        public void Add(T entity)
        {
            _collection.InsertOne(entity);
        }
 
        public void Delete(Expression<Func<T, bool>> predicate)
        {
            var filter = Builders<T>.Filter.Where(predicate);
            _collection.DeleteMany(filter);
        }
 
        public IEnumerable<T> GetAll()
        {
            return _collection.Find(_ => true).ToList();
        }
 
        public T GetByID(string id)
        {
            return _collection.Find<T>(t => t.Id == id).FirstOrDefault();
        }
 
        public T GetOneByCondition(Expression<Func<T, bool>> predicate)
        {
            var filter = Builders<T>.Filter.Where(predicate);
            return _collection.Find(filter).FirstOrDefault();
        }
 
        public void Update(T entity)
        {
            var filter = Builders<T>.Filter.Where(t => t.Id == entity.Id);
            _collection.ReplaceOne(filter, entity);
        }
    }
}这段代码定义了一个泛型的MongoDB仓储类,它实现了IRepository接口。它使用了MongoDB.Driver库来与MongoDB数据库进行交互。代码中包含了基本的CRUD操作,展示了如何使用MongoDB的驱动来操作MongoDB数据库。
