DbCRUD.MongoDB 2.5.3

dotnet add package DbCRUD.MongoDB --version 2.5.3                
NuGet\Install-Package DbCRUD.MongoDB -Version 2.5.3                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DbCRUD.MongoDB" Version="2.5.3" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DbCRUD.MongoDB --version 2.5.3                
#r "nuget: DbCRUD.MongoDB, 2.5.3"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install DbCRUD.MongoDB as a Cake Addin
#addin nuget:?package=DbCRUD.MongoDB&version=2.5.3

// Install DbCRUD.MongoDB as a Cake Tool
#tool nuget:?package=DbCRUD.MongoDB&version=2.5.3                

数据库连接及初始化 Database connection and initialization

 //数据库连接 Database connection
  IDbCRUD testdb =new MongoDbCRUD("mongodb://localhost:27017/testdb");
 //带连接选项初始化数据库连接对象 AutoID(自动编号),RetryConnection(重连,默认true), AutoOpen(是否自动连接),ToLocalTime(默认本地时间,false时UTC)
  ,CreateMetaInfo(创建表列元信息,保存在admin.Tables),CreateFindInfo(创建查询调用信息,保存在admin.FindInfo)
  ,UseChangeCallBack(是否启用数据变化回调,增删改数据回调)
  MongoDbCRUD testdb = new MongoDbCRUD("mongodb://localhost:27017/testdb", 
       opt => opt.AutoID = true; opt.AutoOpen = true; opt.ToLocalTime = false; opt.CreateMetaInfo = true
       ;opt.CreateFindInfo = true;opt.UseChangeCallBack = true);

➕插入数据 Insert data

//*****插入对象数据 Insert object data synchronously
int id = testdb.Max<int>(tb_custormer);
var customer = new CrudTestModel
{
    ID = id + 1,
    Name = "objectData",
    Phones = new string[] { "80000", "90000" },
    FFloat=random.NextDouble(),
    IsActive = true,
    Dic = new Dictionary<string, object>
    {
        { "Name", "Embed_Data" },
        { "DDate", DateTime.Now }
    }
};
var result = testdb.Insert(tb_custormer, customer);
//*****插入字典数据 Insert dictionary data synchronously
var dic1 = new Dictionary<string, object>
{
    { "_id", 0 },//***_id为0时自动编号
    { "Name", "MongodbCRUD" },
    { "Qty",random.Next(1,10000) },
    { "DDATE", DateTime.Now }
};
var dicresult = testdb.Insert(autoIDData, dic1);
//*****插入JSON数据 Insert JSON data 
string jsondata = JsonConvert.SerializeObject(dic1);
var result12 =testdb.Insert(tb_jsondata, jsondata);
//*****SQL语句插入 sql command insert 大小写敏感
var result13 = testdb.Insert($"insert into {sqldata}('name','date') values ('test1','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd")}')");
//*****批量插入列表 Batch insert
List<Dictionary<string, object>> listdata = new List<Dictionary<string, object>>();
int maxid = testdb.Max<int>(dictable);
for (int i = 0; i < 10; i++)
{
    maxid++;
    var dic2 = new Dictionary<string, object>
    {
        { "_id",maxid },
        { "Name", "Batch insert" },
        { "Qty",random.Next(1,10000) },
        { "DDATE", DateTime.Now }
    };
    listdata.Add(dic2);
}
var listResult= testdb.Insert(dictable, listdata);

⬆更新数据 update data

  //【实体对象更新】 更新_id=3的数据 ,字段大小写非敏感,数据大小写敏感。
    CrudTestModel crud = new CrudTestModel() { ID=3,Name="数据中指定了ID,自动更新指定ID的数据"};
    var id_result=testdb.UpDate(tb_custormer, crud);

    //【实体对象根据指定条件更新】 更新_id=1的数据 ,字段大小写非敏感,数据大小写敏感。
    CrudTestModel crud1 = new CrudTestModel() {Name = "根据指定条件更新数据" };
    var where_result = testdb.UpDate(tb_custormer, crud1, "_id=1");

    //【字典数据更新】更新_id=6的数据,字段和数据大小写敏感
    var updata = new Dictionary<string, object>
    {
        { "Name", "更新指定字段数据" },
        { "Qty", 600}
    };
    var upresult = testdb.UpDate(dictable, updata, "_id=6"); 
    //更新后
    var getupdata = testdb.Find<Dictionary<string, object>>(dictable, "_id=6")?.FirstOrDefault();
    Assert.AreEqual(600, getupdata.GetValueOrDefault("Qty", 0));
    //【SQL语句更新】 更新_id=1的数据 ,mongodb对大小写敏感,所有sql语句中的表名和字段名大小写要与DB一致.

    var sql_up_result = testdb.UpDate("UPDATE dicdata SET Name='zzw',Qty=188 where _id=1");
    Assert.IsTrue(sql_up_result.Status); 

🕐更新及插入数据(数据存在更新,不存在插入) Update and insert data (there is an update of the data, but there is no insertion)

    //***** 更新或插入数据 Update or insert data
    var dic1 = new Dictionary<string, object>
    {
        { "_id", 2 },
        { "Name", "Inserts or updates a single piece of data" },
        { "Qty", 200},
        { "DDATE", DateTime.Now }
    };
    var result= testdb.Upsert(dictable, dic1);

   //*****Batch insert or update Batch insert or update
    var dic3 = new Dictionary<string, object>
    {
        { "_id", 3 },
        { "Name", "Batch insert or update" },
        { "Qty", 300},
        { "DDATE", DateTime.Now }
    };
    List<Dictionary<string,object>> listdata=new List<Dictionary<string, object>> { dic3,dic1};
    var listresult = testdb.Upsert(dictable, listdata);

   //*****不存在就插入 Insert if it doesn't exist
    int maxid = testdb.Max<int>(dictable)+1;
    var dic4 = new Dictionary<string, object>
    {
        { "_id", maxid },
        { "Name", "根据_id不存在插入值" },
        { "Qty", 8000},
        { "DDATE", DateTime.Now }
    };
    testdb.Upsert(dictable, dic4);

🔎查询数据 Query data

   ///查找id=2的数据
    var databyid = testdb.FindByID<Dictionary<string, object>>(dictable, 2);

    //查找id=2的数据,返回模型数据。 
    //【注意】模型和数据库中的列数不一致时,需要在模型上加 [BsonIgnoreExtraElements]特性,
    //        mongodb默认时UTC时间,如果要转本地时间,在模型时间属性上加[BsonDateTimeOptions(Kind =DateTimeKind.Local)]特性
    var modeldata = testdb.Find<CrudTestModel1>(tb_custormer, "_id=2")?.FirstOrDefault();

    ///查找id>2的数据,返回按DDATE排序,并排除dic列的最新一条数据
    var ondresult = testdb.FindOne<CrudTestModel>(tb_custormer, "_id>2", project: "!dic", sort: "!DDATE");

    //查找Qty>10的数据
    var wheredata = testdb.Find<Dictionary<string, object>>(dictable, "Qty>10");
    
    //【SQL语法,查找开头】,查找name中'Mongodbi'开头的数据,条件不区分大小写,字段名称区分大小写
    var like_result = testdb.FindAndResult<Dictionary<string, object>>(autoIDData, "Name like'Mongodb%'");

    //【SQL语法,查找结尾】,查找name中'crud'开头的数据,条件不区分大小写,字段名称区分大小写
    var like_result1 = testdb.FindAndResult<Dictionary<string, object>>(autoIDData, "Name like'%crud'");

    //【SQL语法,包含】,查找name中包含'odb'的数据,条件不区分大小写,字段名称区分大小写
    var like_result2 = testdb.FindAndResult<Dictionary<string, object>>(autoIDData, "Name like'%odb%'");
    
    //【MongoDB语法】,查找name中'Mongodbi'开头的数据,不区分大小写
    var bsonwheredata = testdb.Find<Dictionary<string, object>>(autoIDData, "{Name:/^Mongodb/i}");
    
    //****SQL语法和Mongodb查询语法不能混用,简单查询使用SQL语法,书写简单,复杂查询只能使用原生语法。
    //【简写语法】分页查找Qty>10,返回除_id列,按DDATE倒序排序的数据,返回第一页10条数据。
    var pagedata = testdb.GetPagingData<Dictionary<string, object>>(tb_jsondata, "Qty>10",project:"!_id",sort: "!DDATE", pageindex: 1, pagecount: 10);
    
    //【Mongodb语法】分页查找Qty>10,返回除_id列,按DDATE倒序排序的数据,返回第一页10条数据。
    var mgdb_pagedata = testdb.GetPagingData<Dictionary<string, object>>(tb_jsondata, "{Qty:{$gt:10}}", project: "{_id:0}", sort: "{DDATE:-1}", pageindex: 1, pagecount: 10);
    
    //【返回DataTable】分页查找Qty>10,返回除_id列,按DDATE倒序排序的数据,返回第一页10条数据。
    var datatable_pagedata = testdb.GetPagingData(autoIDData, "Qty>10", project: "!_id", sort: "!DDATE", pageindex: 1, pagecount: 10);
   
    //【多条件查询】分页查找Qty>10,返回除_id列,按DDATE倒序排序的数据,返回第一页10条数据。
    var mu_where = testdb.GetPagingData<Dictionary<string, object>>(dictable, "_id>=6 and Qty>10", sort: "!DDATE", pageindex: 1, pagecount: 10);
   
    //【日期范围查询】查找DDATE>='2023-06-05 09:12:24' 和 DDATE<='2023-06-05 13:28:48'的数据,按DDATE倒序。
    var date_result = testdb.GetPagingDataAndResult<Dictionary<string, object>>(dictable, "DDATE>='2023-06-05 09:12:24' and DDATE<='2023-06-05 13:28:48'", sort: "!DDATE", pageindex: 1, pagecount: 10);
    
    //【in查询】查找Qty=200和300的数据。
    var in_result = testdb.GetPagingDataAndResult<Dictionary<string, object>>(dictable, "Qty in(200,300)", sort: "!DDATE", pageindex: 1, pagecount: 10);
   
    //【in模糊查询】查找Name=Batch insert和data结尾的数据。
    var in_fuzzy = testdb.GetPagingDataAndResult<Dictionary<string, object>>(dictable, "Name in('Batch insert','%data')", sort: "!DDATE", pageindex: 1, pagecount: 10);

    //【正则表达式查询】查找Name=Batch开头的数据。
    var in_regex = testdb.GetPagingDataAndResult<Dictionary<string, object>>(dictable, "Name reg'^Batch'", sort: "!DDATE", pageindex: 1, pagecount: 10);s
    //【sql语句查询】查找_id=1的数据
    string sqlcmd = $"select _id,Name,DDATE from {dictable} where _id=1";
    var sqldata = testdb.Find<Dictionary<string, object>>(sqlcmd);
    //【委托查询】查找_id>=6 and Qty>10的数据。数据在委托中返回,方便进行数据处理
    var action_result = testdb.GetPagingDataAction<CrudTestModel1>(dictable, "_id>=6 and Qty>10", datalist => 
    {
        double sum = datalist.Sum(s => s.FFloat);
                
    });
    var link_where = testdb.FindAndResult<CrudTestModel>(tb_custormer, q=>q.ID>6 && q.ID<=10 && q.Name.Contains("obje"));

➖删除数据 delete data

    //**删除ID=8的数据
    var result = testdb.Delete(dictable, 8);

    //**删除qty>10的数据
     var wherresult = testdb.Delete(dictable, "_id>=10");
    //**使用sql语句删除ID = 7的数据,大小写敏感
    string sql = $"delete from {dictable} where _id=7";
    var sqlresult = testdb.Delete(sql);

📑创建索引

 //创建Name和P_Name升序索引
 var r= testdb.CreateIndex(tb, strIndexs: "Name,P_Name", dbName: "testdb");
 //创建DDATE降序索引
 var r1= testdb.CreateIndex(tb, strIndexs: "!DDATE", dbName: "testdb");
 创建DDATE和P_Name升序命名为DDATEPname的索引
 var r1 = testdb.CreateIndex(tb, strIndexs: "DDATE,P_Name", indexName: "DDATEPname", dbName: "testdb");

Key-Value增删改查

//单值key-value string key = "test"; var v = DateTime.Now; //保存 var result = testdb.SaveKeyValue(key, v); //判断是否存在 bool isExists= testdb.KeyValueExists(key) //获取 var getv = testdb.GetKeyValue<DateTime>(key); //删除 bool ok= testdb.DelKeyValue(key) //对象key-value var crud_result = testdb.FindAndResult<CrudTestModel>(tb_custormer, $"{testdb.IdName}=1"); if (crud_result.Data != null) { //单对象 string objkey = "object_keyvalue"; var obj_result = testdb.SaveKeyValue(objkey, crud_result.Data.FirstOrDefault()); Assert.IsTrue(obj_result.State); Assert.IsTrue(testdb.KeyValueExists(objkey)); var objv = testdb.GetKeyValue<CrudTestModel>(objkey); Assert.IsTrue(objv.ID>0); //数组列表 string arraykey = "array_keyvalue"; var arraykey_result = testdb.SaveKeyValue(arraykey, crud_result.Data); Assert.IsTrue(arraykey_result.State); Assert.IsTrue(testdb.KeyValueExists(arraykey)); var arraykeyv = testdb.GetKeyValue<IEnumerable<CrudTestModel>>(arraykey); Assert.IsTrue(arraykeyv.Count()>0); }

消息事件绑定(可日志输出)

    public DbTest() {
    t estdb.Message += Testdb_Message;
    }

    private void Testdb_Message((string Message, string Level, DateTime Time) obj)
    {
       Debug.WriteLine($"{obj.Time}|{obj.Level}|{obj.Message}");
    }

增删改查系列包

一致的增删改查语法

LiteDB

IDbCRUD testdb = new LiteDbCRUD(@"filename=CRUDTestDB.db");
//【日期范围查询】查找DDATE>='2023-06-05 09:12:24' 和 DDATE<='2023-06-05 13:28:48'的数据。
var date_result = testdb.GetPagingDataAndResult<Dictionary<string, object>>(dictable, $"DDATE>='2023-06-05 09:12:24' and DDATE<='{DateTime.Now:yyyy-MM-dd HH:mm:ss}'");

MongoDB

IDbCRUD testdb =new MongoDbCRUD("mongodb://localhost:27017/testdb");
//【日期范围查询】查找DDATE>='2023-06-05 09:12:24' 和 DDATE<='2023-06-05 13:28:48'的数据。
var date_result = testdb.GetPagingDataAndResult<Dictionary<string, object>>(dictable, $"DDATE>='2023-06-05 09:12:24' and DDATE<='{DateTime.Now:yyyy-MM-dd HH:mm:ss}'");

Mysql

IDbCRUD testdb = new MysqlCRUD(@"Server=127.0.0.1;Database=testdb;Uid=root;Pwd=;");

//【日期范围查询】查找DDATE>='2023-06-05 09:12:24' 和 DDATE<='2023-06-05 13:28:48'的数据。
var date_result = testdb.GetPagingDataAndResult<Dictionary<string, object>>(dictable, $"DDATE>='2023-06-05 09:12:24' and DDATE<='{DateTime.Now:yyyy-MM-dd HH:mm:ss}'");

Sqlite

IDbCRUD testdb = new SqliteCRUD($@"Data Source=sqlitedb.db; Cache=Shared")

//【日期范围查询】查找DDATE>='2023-06-05 09:12:24' 和 DDATE<='2023-06-05 13:28:48'的数据。
var date_result = testdb.GetPagingDataAndResult<Dictionary<string, object>>(dictable, $"DDATE>='2023-06-05 09:12:24' and DDATE<='{DateTime.Now:yyyy-MM-dd HH:mm:ss}'");

SQL SERVER

IDbCRUD testdb = new SqlServerCRUD(@"Data Source=xxx;Initial Catalog=xxx;User ID=sa;Password=xxx;Encrypt=True;TrustServerCertificate=True;");
//【日期范围查询】查找DDATE>='2023-06-05 09:12:24' 和 DDATE<='2023-06-05 13:28:48'的数据。
var date_result = testdb.GetPagingDataAndResult<Dictionary<string, object>>(dictable, $"DDATE>='2023-06-05 09:12:24' and DDATE<='{DateTime.Now:yyyy-MM-dd HH:mm:ss}'");

实体模型

     [BsonIgnoreExtraElements]
    public class CrudTestModel1
    {
        [BsonId]
        public int ID { get; set; }
        public string Name { get; set; }
        public string[] Phones { get; set; }
        public bool IsActive { get; set; }
        public double FFloat { get; set; } = 0.118;
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime DDATE { get; set; } = DateTime.Now;

    }

后续开发计划

增加查询记录,查询计划信息反馈 查询增加总记录数返回 优化索引创建 保持列序

  • 增加查询条件大小写脱敏
  • 增加修改保存大小写脱敏
  • 增加自动编号并发处理
  • 解决字典属性null保存失败问题
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.5.3 96 12/9/2024
2.5.2 94 12/4/2024
2.5.1 85 11/28/2024
2.5.0 101 11/11/2024
2.4.9 96 10/24/2024
2.4.8 81 10/23/2024
2.4.7 106 9/22/2024
2.4.6 132 8/23/2024
2.4.5 110 8/7/2024
2.4.4 111 7/2/2024
2.4.3 98 6/26/2024
2.4.2 99 6/24/2024
2.4.1 136 4/30/2024
2.4.0 119 4/27/2024
2.3.9 124 4/24/2024
2.3.8 122 4/21/2024
2.3.7 117 4/17/2024
2.3.6 121 4/16/2024
2.3.5 111 4/15/2024
2.3.4 114 4/15/2024
2.3.3 128 4/14/2024
2.3.2 130 4/10/2024
2.3.1 102 4/9/2024
2.3.0 118 4/8/2024
2.2.2 112 4/7/2024
2.2.1 114 4/6/2024
2.2.0 114 4/1/2024
2.1.3 121 3/29/2024
2.1.2 116 3/29/2024
2.1.1 127 3/27/2024
2.1.0 115 3/22/2024
2.0.9 111 3/21/2024
2.0.8 120 3/20/2024
2.0.7 121 3/16/2024
2.0.6 127 3/15/2024
2.0.5 125 3/14/2024
2.0.4 126 3/13/2024
2.0.3 123 3/13/2024
2.0.2 112 3/12/2024
2.0.1 134 3/11/2024
2.0.0 144 3/10/2024
1.6.7 121 3/1/2024
1.6.6 165 1/10/2024
1.6.5 130 1/10/2024
1.6.4 154 12/21/2023
1.6.3 138 12/15/2023
1.6.2 116 12/15/2023
1.6.1 106 12/15/2023
1.6.0 106 12/15/2023
1.5.9 115 12/13/2023
1.5.8 116 12/12/2023
1.5.7 129 12/12/2023
1.5.6 132 12/2/2023
1.5.5 118 11/30/2023
1.5.4 127 11/27/2023
1.5.3 126 11/27/2023
1.5.2 136 11/24/2023
1.5.1 137 11/21/2023
1.5.0 139 11/15/2023
1.4.9 122 11/13/2023
1.4.8 123 11/10/2023
1.4.7 163 10/22/2023
1.4.6 161 9/4/2023
1.4.5 147 9/3/2023
1.4.4 176 8/27/2023
1.4.3 174 8/4/2023
1.4.2 157 7/31/2023
1.4.1 161 7/29/2023
1.4.0 173 7/26/2023
1.3.9 177 7/24/2023
1.3.8 178 7/23/2023
1.3.7 166 7/21/2023
1.3.6 164 7/20/2023
1.3.5 170 7/19/2023
1.3.4 184 7/15/2023
1.3.3 157 7/14/2023
1.3.2 162 7/13/2023
1.3.1 159 7/13/2023
1.3.0 169 7/10/2023
1.2.9 156 6/26/2023
1.2.8 156 6/23/2023
1.2.7 155 6/18/2023
1.2.6 154 6/16/2023
1.2.5 167 6/15/2023
1.2.4 164 6/13/2023
1.2.3 170 6/11/2023
1.2.2 160 6/10/2023
1.2.1 168 6/9/2023
1.2.0 160 6/8/2023
1.1.2 149 6/7/2023
1.1.1 135 6/6/2023
1.0.0 172 6/5/2023

1. mongodb降包,以兼容旧数据库版本
2. 增加数据替换方法
3. 增删改查大小写转换,增加可选配置