mongodb在C#的连接以及curd写法

连接数据库:参考地址:https://blog.oz-code.com/how-to-mongodb-in-c-part-2/

        // Empty ctor will get you a
        // client with a default localhost and port #27017
        MongoClient m = new MongoClient();
        //----------------------------------------------------------------------
        // Using a connection-string
        MongoClient m1 = new MongoClient("mongodb://localhost:27017");
        //----------------------------------------------------------------------
        // Using MongoClientSettings
        MongoClient client = new MongoClient(
         new MongoClientSettings
         {
             Server = new MongoServerAddress("localhost", 27018),
                 // Giving 3 seconds for a MongoDB server to be up before we throw
                 ServerSelectionTimeout = TimeSpan.FromSeconds(3)
         });
        //----------------------------------------------------------------------
        // Using MongoUrl
        MongoClient client1 = new MongoClient(
         MongoUrl.Create("mongodb://localhost:27017"));
    }

CURD:

MongoClient mongoClient = new MongoClient(configuration["DataBaseConnection:0:host"]);
                var dbAdmin = mongoClient.GetDatabase("shoppingMall");
                var buyerCollection = dbAdmin.GetCollection<Buyer>("shoppingMall.buyer");
                //新增
                ////var a= buyerCollection.InsertOneAsync(new Buyer { buyerName="管理员", buyerAge=23, buyerAddress="江汉市天府大道067号", buyerSex=‘0‘, buyerIdCard="12355544884474", buyerHeadPortrait="~/images/admin.jpg", buyerAccountNumber="admin1" });
                //查询
                //linq写法
                //var sql = from bb in buyerCollection.AsQueryable()
                //          select bb;
                //sql= sql.Where(t => t.buyerAge >= 22);
                //var retlist = sql.ToList();
                //ef写法
                //var ret = buyerCollection.AsQueryable().GroupBy(t=>new { t.buyerAge }).Where(t=>t.Key.buyerAge>=22);
                //var b = ret.ToList();

                var filterBuilder = Builders<Buyer>.Filter;
                var filter = filterBuilder.Gt("buyerAge", 10) & filterBuilder.Lt("counter", 30) & filterBuilder.Lt("counter", 30);//多个条件

                //var filter = Builders<Buyer>.Filter.Gt("buyerAge", 1);//一个条件
                var document = await buyerCollection.FindAsync(filter);
                var res = document.ToList();

                //更新
                var updateFilter = filterBuilder.Gt("buyerAge", 20) & filterBuilder.Lt("buyerAge", 30);//多个条件

                var updated = Builders<Buyer>.Update.Set("buyerName", "李四");
                var result = buyerCollection.UpdateManyAsync(updateFilter, updated).Result;

                //删除
                var delFilter = filterBuilder.Gt("buyerAge", 20) & filterBuilder.Lt("buyerAge", 30);//多个条件

                var resut = buyerCollection.DeleteManyAsync(delFilter).Result;

其中:

configuration["DataBaseConnection:0:host"]属于。netcore的连接字符串写法。具体实现如下:

appsettings.json:

"DataBaseConnection": [
    {
      "host": "mongodb://localhost:27017"
    }
  ]

读取方法:

        public IConfigurationRoot configuration;
        public BaseController()
        {
            //读取appsettings配置
            var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");
            configuration = builder.Build();
        }

原文地址:https://www.cnblogs.com/llcdbk/p/9011672.html

时间: 2024-08-15 05:40:10

mongodb在C#的连接以及curd写法的相关文章

windows下mongodb基础玩法系列二CURD操作(创建、更新、读取和删除)

windows下mongodb基础玩法系列 windows下mongodb基础玩法系列一介绍与安装 windows下mongodb基础玩法系列二CURD操作(创建.更新.读取和删除) 简单说几句 在mongodb中3元素:db(数据库).collection(集合).document(文档) 其中collection类似于数据库中的表,document类似于行,这样一来我们就将内容对比起来记忆学习了. 数据格式 MongoDB documents是BSON格式(一种类json的一种二进制形式的存

mongodb远程数据库的连接以及备份导入导出数据

环境win10; 运行cmd cd到目录mongodb的bin目录: 连接远程mongodb: 连接命令:mongo -u username -p pwd host:post/database(数据库名) 当该用户有相应权限时,可以查看collection==>查看集合命令:show collections 导出命令:mongodump -h IP --port 端口 -u 用户名 -p 密码 -d 数据库 -o 文件存在路径 详细解释: -h:mongodb所在的服务器地址(必须指定端口),不

windows下mongodb基础玩法系列二CURD附加一

windows下mongodb基础玩法系列 windows下mongodb基础玩法系列一介绍与安装 windows下mongodb基础玩法系列二CURD操作(创建.更新.读取和删除) windows下mongodb基础玩法系列二CURD附加一 说在前面的话 在系列二中CURD只是简单的走了一下代码操作的流程,其中全是简单基础操作的内容, 在我仔细看完接下来的内容后决定再丰富一下前面的操作,并实战一个简单的demo出来,demo具体搭配语言暂时决定在PHP与nodejs之间. 增加内容至文档没说完

Ado访问sqlserver 端口号非1433时 连接串的写法

Ado访问sqlserver 端口号非1433时 连接串的写法 Provider=SQLOLEDB.1;Persist Security Info=False;Data Source=hostName,Port //注意用 逗号分隔主机名与端口号

mongodb or操作与连接池

mongodb # 类似于sql中的in或者or操作 mulites field query: db.cool.find({$or:[{field1:'val'},{'field2':'val'}-]}) # 类似于sql中的like操作 db.coo.find('name': /m/) == sql like pymongo 使用 {'field':{$regex: keyword}} http://stackoverflow.com/questions/3305561/how-do-i-qu

【数据库】Mean web开发 05-Linux上配置MongoDB自动启动及远程连接

简介 Mean是JavaScript的全栈开发框架.更多介绍 用MongoDB实现持久数据的存储是Mean Web全栈开发中的一部分. MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的.它的特点是高性能.易部署.易使用,存储数据非常方便. MongoDB的学习资料可参考: MongoDB中文社区 上一节介绍了MongoDB在Linux上的安装及遇到的问题,这一节介绍MongoDB在Linux上的自动启动及远程连接. 在Linux上自动启动

mongodb c# driver(驱动)介绍及CURD

mongodb c# driver(驱动)介绍 目前基于C#的mongodb驱动有两种,分别是官方驱动(下载地址)和samus驱动(下载地址). 本次我们只演示官方驱动的使用方法. 官方驱动文档查看 第一步:引用驱动dll 引用驱动有两种方式: 1. 根据上面的下载地址下载对应的版本,然后引用到项目中. 2. 在项目的引用上右击->管理NuGet程序包(首先确保安装了nuget扩展包)->联机搜索官方驱动dll(搜索条件是 “Official MongoDB”)->安装成功后会引用3个d

MongoDB【UVE】 - 连接Connection

简单的填写你所需要连接的MongoDB的库,即可. 这里为了方便,我们的名字也就是Server的 IP地址 simple Tips , 简单的记录.

mongodb添加远程用户连接

默认mongodb刚刚安装完是没有用户密码的直接登录即可 > mongo MongoDB shell version: 2.2.0 connecting to: test > use admin   switched to db admin > db.addUser("root", "123456") ok,这样我们就建立好了超级管理员的账号和密码. 第三步,登录认证 > db.auth("root","1234