C# 使用mongodb 帮助类

在C#中使用MongoDB,你需要安装MongoDB的C#驱动程序,通常使用MongoDB.Driver。

以下是一个简单的帮助类,用于连接MongoDB数据库并执行基本的CRUD操作。

首先,通过NuGet安装MongoDB.Driver:

Install-Package MongoDB.Driver

复制代码
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
 
public static class MongoDBHelper<T> where T : class
{
    private static IMongoCollection<T> _collection;
 
    static MongoDBHelper()
    {
        var connectionString = "your_mongodb_connection_string";
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase("your_database_name");
        _collection = database.GetCollection<T>("your_collection_name");
    }
 
    public static List<T> GetAll()
    {
        return _collection.Find(new BsonDocument()).ToList();
    }
 
    public static T GetById(string id)
    {
        return _collection.Find(Builders<T>.Filter.Eq("_id", id)).FirstOrDefault();
    }
 
    public static T GetSingle(Expression<Func<T, bool>> predicate)
    {
        return _collection.Find(predicate).FirstOrDefault();
    }
 
    public static void Insert(T entity)
    {
        _collection.InsertOne(entity);
    }
 
    public static void Update(T entity)
    {
        _collection.ReplaceOne(Builders<T>.Filter.Eq("_id", entity.Id), entity);
    }
 
    public static void Delete(string id)
    {
        _collection.DeleteOne(Builders<T>.Filter.Eq("_id", id));
    }
}
复制代码

使用该帮助类

复制代码
public class MyEntity
{
    public string Id { get; set; }
    public string Name { get; set; }
}
 
// 获取所有记录
List<MyEntity> entities = MongoDBHelper<MyEntity>.GetAll();
 
// 通过ID获取单个记录
MyEntity entity = MongoDBHelper<MyEntity>.GetById("some_id");
 
// 插入新记录
MyEntity newEntity = new MyEntity { Name = "New Entity" };
MongoDBHelper<MyEntity>.Insert(newEntity);
 
// 更新记录
newEntity.Name = "Updated Name";
MongoDBHelper<MyEntity>.Update(newEntity);
 
// 删除记录
MongoDBHelper<MyEntity>.Delete("some_id");
复制代码

 

posted @   天天向上518  阅读(66)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
历史上的今天:
2019-11-06 Layer.js弹层的一些简单的使用
2019-11-06 Sqlserver表值函数来获取逗号分隔的ID
点击右上角即可分享
微信分享提示