使用C#实现mongodb的CRUD

引用的类库

    <ItemGroup>
        <PackageReference Include="MongoDB.Bson" Version="2.19.0" />
        <PackageReference Include="MongoDB.Driver" Version="2.19.0" />
        <PackageReference Include="MongoDB.Driver.Core" Version="2.19.0" />
        <PackageReference Include="CsvHelper" Version="29.0.0" />
        <PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
    </ItemGroup

代码实现

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
using System.Data;
using System.Text;
using Yxing.MongoDBSystem.JsonData;

namespace Utilities.MongoDBLib
{
    public class MongoDBCRUD
    {


        MongoClient client;
        IMongoDatabase database;
        IMongoCollection<BsonDocument> collection;


        public MongoDBCRUD(MongoClient client,IMongoDatabase database)
        {
            this.client = client;
            this.database=database;
        }

        public MongoDBCRUD()
        {
            client = new MongoClient("mongodb://localhost:27017");
            database = client.GetDatabase("FileSystem");

        }
         //使用CSVhelper库 导出CSV文档
        //name:保留字段,无意义
        //collectionName:集合名称
        public async Task<bool> ReadyCsvHelperAsync(string name, string collectionName)
        {
            this.collection = database.GetCollection<BsonDocument>(collectionName);
            try
            {
                using (var writer = new StreamWriter("data.csv", false, Encoding.UTF8))
                {
                    var cursor = await this.collection.FindAsync(new BsonDocument());
                    var documents = await cursor.ToListAsync();
                    var fieldNames = documents.First().Names.ToList();
                    fieldNames.Remove("_id");
                    writer.WriteLineAsync(string.Join(",", fieldNames));

                    foreach (var document in documents)
                    {
                        var values = fieldNames.Select(fieldName =>
                        {
                            var value = document.GetValue(fieldName, BsonNull.Value);
                            return value == BsonNull.Value ? "" : value.ToString();
                        });
                        await writer.WriteLineAsync(string.Join(",", values));
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }

        }
        //使用CSVhelper库 导出CSV文档
        //name:保留字段,无意义
        //collectionName:集合名称
        public bool ReadByCsvHelper(string name, string collectionName)
        {
            this.collection = database.GetCollection<BsonDocument>(collectionName);
            try
            {
                using (var writer = new StreamWriter("data.csv", false, Encoding.UTF8))
                {
                    var cursor = this.collection.Find(new BsonDocument());
                    var documents = cursor.ToList();
                    var fieldNames = documents.First().Names.ToList();
                    fieldNames.Remove("_id");
                    writer.WriteLine(string.Join(",", fieldNames));

                    foreach (var document in documents)
                    {
                        var values = fieldNames.Select(fieldName =>
                        {
                            var value = document.GetValue(fieldName, BsonNull.Value);
                            return value == BsonNull.Value ? "" : value.ToString();
                        });
                        writer.WriteLine(string.Join(",", values));
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;

            }

        }
        //从web 导出 指定 名字的colletion
        public FileStreamResult ReadByWeb(string collectionName)
        {
            var collection = database.GetCollection<BsonDocument>(collectionName);
            MemoryStream stream = new MemoryStream();

            StreamWriter writer = new StreamWriter(stream);

            List<BsonDocument> documents = collection.Find(new BsonDocument()).ToList();
            IEnumerable<string> headers = documents.First().Names;


            writer.WriteLine(string.Join(",", headers));

            foreach (var document in documents)
            {
                var values = document.Values.Select(v => v.ToString()).ToArray();
                writer.WriteLine(string.Join(",", values));
            }

            writer.Flush();
            stream.Position = 0;
            FileStreamResult content = new FileStreamResult(stream, "text/csv");
            content.FileDownloadName = collectionName;
            return content;

        }

        //从web 端插入 CSV文档, 
        //collecion : 文档名称
        //type:用途
        //describe:描述
        public bool InsertByMongoDB(IFormFile file, string collectionName, string type, string describe)
        {
            var collection = database.GetCollection<BsonDocument>(collectionName);
            try
            {
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                    //读取CSV文件头
                    var header = reader.ReadLine().Split(',');

                    //读取每行数据并插入MongoDB数据库
                    while (!reader.EndOfStream)
                    {
                        var line = reader.ReadLine();
                        var values = line.Split(',');

                        //创建键/值对字典并插入MongoDB数据库
                        var document = new Dictionary<string, object>();
                        for (int i = 0; i < header.Length; i++)
                        {
                            document.Add(header[i], values[i]);
                        }
                        collection.InsertOne(new BsonDocument(document));
                    }
                }
                collection.InsertOne(new BsonDocument()
                    {
                            { "type",type },
                            {"describe",describe },
                            {"DateTime",DateTime.Now.ToString()}

                        });
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        //查询跟文档关联的 type ,描述,跟创建日期
        public List<Dictionary<string, List<Dictionary<string, string>>>> QueryAllColletionInfo()
        {
            var res = database.ListCollectionNames().ToList();
            List<Dictionary<string, List<Dictionary<string, string>>>> result = new List<Dictionary<string, List<Dictionary<string, string>>>>();
            foreach (var item in res)
            {
                var collection = database.GetCollection<BsonDocument>(item);
                var filter = Builders<BsonDocument>.Filter.Empty;
                var projection = Builders<BsonDocument>.Projection.Include("type").Include("describe").Include("DateTime");

                var cursor = collection.Find(filter).Project(projection).ToList().Last();
                IEnumerable<BsonElement> resa = cursor.Where(x => x.Name != "_id");
                List<Dictionary<string, string>> temp = new();
                foreach (var items in resa)
                {
                    temp.Add(new Dictionary<string, string>
                    {
                        {items.Name.ToString(),items.Value.ToString()}
                    });
                }

                result.Add(new Dictionary<string, List<Dictionary<string, string>>>
                {
                    {item.ToString(),temp }
                });
            }
            return result;
        }


        //更新mongodb文档中某一个colletion 某一字段或者某一行,查询的主键是  MeasuringPointName
        public async Task Update(string collectionName, string measuringPointName, List<Dictionary<string, string>> data)
        {
            var collection = database.GetCollection<BsonDocument>(collectionName);

            var filter = Builders<BsonDocument>.Filter.Eq("MeasuringPointName", measuringPointName);
            var updateBuilder = Builders<BsonDocument>.Update;
            BsonDocument bsonElements = new BsonDocument();
            List<Dictionary<string, string>> pairs = new List<Dictionary<string, string>>();

            foreach (var items in data)
            {
                foreach (var item in items)
                {
                    bsonElements.Add(item.Key, item.Value);
                }
            }
            var update = updateBuilder.Combine(bsonElements.Select(u => updateBuilder.Set(u.Name, u.Value)));
            var result = collection.UpdateOne(filter, update);

        }

        //删除
        public bool Delete(string collectionName)
        {
            bool isCollectionExistsBefore = database.ListCollections().ToList().Any(x => x["name"].AsString == collectionName);
            database.DropCollection(collectionName);
            bool isCollectionExistsAfter = database.ListCollections().ToList().Any(x => x["name"].AsString == collectionName);

            if (isCollectionExistsBefore && !isCollectionExistsAfter)
            {
                return true;

            }
            else
            {
                return false;
            }
        }

    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值