From cde25a64172b243c6bd5950a838138510d9f8062 Mon Sep 17 00:00:00 2001 From: sunkaixuan <610262374@qq.com> Date: Thu, 8 May 2025 20:02:51 +0800 Subject: [PATCH] Update mongodb --- .../MongoDbTest/OrmTest/OrmTest.cs | 21 +++++++-- .../ExpToSql/ExpressionVisitor.cs | 3 ++ .../MethodCallExpressionTractor.cs | 27 +++++++++++ .../SqlBuilder/MongoDbUpdateBuilder.cs | 45 ++++++++++++++----- .../MongoDb/Updateable/MongoDbUpdateable.cs | 32 +++++++++++++ .../Tools/UtilExtensions.cs | 4 ++ .../SqlSugar.MongoDbCore/Tools/UtilMethods.cs | 9 +++- 7 files changed, 127 insertions(+), 14 deletions(-) create mode 100644 Src/Asp.NetCore2/SqlSugar.MongoDbCore/ExpToSql/VisitorItems/MethodCallExpressionTractor.cs create mode 100644 Src/Asp.NetCore2/SqlSugar.MongoDbCore/MongoDb/Updateable/MongoDbUpdateable.cs diff --git a/Src/Asp.NetCore2/MongoDbTest/OrmTest/OrmTest.cs b/Src/Asp.NetCore2/MongoDbTest/OrmTest/OrmTest.cs index 5113b89dc..e15f56208 100644 --- a/Src/Asp.NetCore2/MongoDbTest/OrmTest/OrmTest.cs +++ b/Src/Asp.NetCore2/MongoDbTest/OrmTest/OrmTest.cs @@ -22,13 +22,28 @@ namespace MongoDbTest .ExecuteReturnPkList(); - var updateRow = db.Updateable(new List() + var updateRow1 = db.Updateable(new OrderInfo { - new OrderInfo() { Id = ids.First(),Name="a3",Price=11}, - new OrderInfo() { Id = ids.Last(),Name="a4"} + Id = ids.First(), + Name = "a3", + Price = 11 + } + ) + .ExecuteCommand(); + + var updateRow2 = db.Updateable(new List() + { + new OrderInfo() { Id = ids.First(),Name="a31",Price=11}, + new OrderInfo() { Id = ids.Last(),Name="a41"} }) .ExecuteCommand(); + + var updateRow3= db.Updateable() + .SetColumns(it=>it.Name=="aa") + .Where(it=>it.Id==ids.Last()) + .ExecuteCommand(); + var delrow = db.Deleteable(new OrderInfo() { Id = ids.Last() }) .ExecuteCommand(); diff --git a/Src/Asp.NetCore2/SqlSugar.MongoDbCore/ExpToSql/ExpressionVisitor.cs b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/ExpToSql/ExpressionVisitor.cs index bd9e0e4a1..620d801f0 100644 --- a/Src/Asp.NetCore2/SqlSugar.MongoDbCore/ExpToSql/ExpressionVisitor.cs +++ b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/ExpToSql/ExpressionVisitor.cs @@ -2,6 +2,7 @@ using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; +using System.Data; using System.Linq.Expressions; using System.Text; @@ -39,6 +40,8 @@ namespace SqlSugar.MongoDbCore return this.Visit(unary); case LambdaExpression lambda: return this.Visit(lambda.Body); + case MethodCallExpression call: + return new MethodCallExpressionTractor(context, visitorContext).Extract(call); default: throw new NotSupportedException($"Unsupported expression: {expr.NodeType}"); } diff --git a/Src/Asp.NetCore2/SqlSugar.MongoDbCore/ExpToSql/VisitorItems/MethodCallExpressionTractor.cs b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/ExpToSql/VisitorItems/MethodCallExpressionTractor.cs new file mode 100644 index 000000000..fa7fe1d6b --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/ExpToSql/VisitorItems/MethodCallExpressionTractor.cs @@ -0,0 +1,27 @@ +using MongoDB.Bson; +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Text; + +namespace SqlSugar.MongoDbCore +{ + public class MethodCallExpressionTractor + { + MongoNestedTranslatorContext _context; + ExpressionVisitorContext _visitorContext; + public MethodCallExpressionTractor(MongoNestedTranslatorContext context, ExpressionVisitorContext visitorContext) + { + _context = context; + _visitorContext = visitorContext; + } + public BsonValue Extract(Expression expr) + { + if (ExpressionTool.GetParameters(expr).Count == 0) + { + return BsonValue.Create(ExpressionTool.DynamicInvoke(expr)); + } + return null; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.MongoDbCore/MongoDb/SqlBuilder/MongoDbUpdateBuilder.cs b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/MongoDb/SqlBuilder/MongoDbUpdateBuilder.cs index c34769eb5..3199d55f5 100644 --- a/Src/Asp.NetCore2/SqlSugar.MongoDbCore/MongoDb/SqlBuilder/MongoDbUpdateBuilder.cs +++ b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/MongoDb/SqlBuilder/MongoDbUpdateBuilder.cs @@ -1,4 +1,5 @@ using MongoDB.Bson; +using MongoDB.Bson.Serialization; using System; using System.Collections.Generic; using System.Linq; @@ -49,7 +50,40 @@ namespace SqlSugar.MongoDb { var operations = new List(); List pks = this.PrimaryKeys; + if (this.SetValues.Any()) + { + var setOperation = new BsonDocument(); + foreach (var item in this.SetValues) + { + var bson = BsonSerializer.Deserialize(item.Value); + foreach (var element in bson) + { + setOperation[element.Name] = element.Value; + } + } + var filterArray = new BsonArray(); + foreach (var item in this.WhereValues) + { + var bson = BsonDocument.Parse(item); // 直接解析 JSON 为 BsonDocument + filterArray.Add(bson); // 将每个条件添加到数组 + } + var filter = new BsonDocument("$and", filterArray); + operations.Add($"{{ filter: {filter.ToJson(UtilMethods.GetJsonWriterSettings())} , update: {{ $set: {setOperation.ToJson(UtilMethods.GetJsonWriterSettings())} }} }}"); + } + else + { + UpdateByObject(groupList, operations, pks); + } + var sb = new StringBuilder(); + sb.Append($"updateMany {tableName} [ "); + sb.Append(string.Join(", ", operations)); + sb.Append(" ]"); + return sb.ToString(); + } + + private static void UpdateByObject(List> groupList, List operations, List pks) + { foreach (var group in groupList) { var filter = new BsonDocument(); @@ -57,7 +91,7 @@ namespace SqlSugar.MongoDb foreach (var col in group) { - + if (col.IsPrimarykey || pks.Contains(col.DbColumnName)) { filter[col.DbColumnName] = BsonValue.Create(ObjectId.Parse(col.Value?.ToString())); ; @@ -87,15 +121,6 @@ namespace SqlSugar.MongoDb operations.Add(json); } - - var sb = new StringBuilder(); - sb.Append($"updateMany {tableName} [ "); - sb.Append(string.Join(", ", operations)); - sb.Append(" ]"); - - return sb.ToString(); } - - } } diff --git a/Src/Asp.NetCore2/SqlSugar.MongoDbCore/MongoDb/Updateable/MongoDbUpdateable.cs b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/MongoDb/Updateable/MongoDbUpdateable.cs new file mode 100644 index 000000000..087507460 --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/MongoDb/Updateable/MongoDbUpdateable.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using MongoDB.Bson; + +namespace SqlSugar.MongoDb +{ + public class MongoDbUpdateable:UpdateableProvider where T:class,new() + { + public override IUpdateable SetColumns(Expression> columns) + { + ThrowUpdateByObject(); + var binaryExp = columns.Body as BinaryExpression; + Check.Exception(!binaryExp.NodeType.IsInValues(ExpressionType.Equal), "No support {0}", columns.ToString()); + Check.Exception(!(binaryExp.Left is MemberExpression) && !(binaryExp.Left is UnaryExpression), "No support {0}", columns.ToString()); + Check.Exception(ExpressionTool.IsConstExpression(binaryExp.Left as MemberExpression), "No support {0}", columns.ToString()); + + var expResult = UpdateBuilder.GetExpressionValue(columns, ResolveExpressType.WhereSingle).GetResultString().Replace(")", " )").Replace("(", "( ").Trim().TrimStart('(').TrimEnd(')').Replace("= =", "="); + var bson = MongoDB.Bson.Serialization.BsonSerializer.Deserialize(expResult); + foreach (var element in bson) + { + string key = element.Name; + BsonValue value = element.Value; + this.UpdateBuilder.SetValues.Add(new KeyValuePair(key, expResult)); + } + return this; + } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar.MongoDbCore/Tools/UtilExtensions.cs b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/Tools/UtilExtensions.cs index 8eb87c37c..2cf853a40 100644 --- a/Src/Asp.NetCore2/SqlSugar.MongoDbCore/Tools/UtilExtensions.cs +++ b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/Tools/UtilExtensions.cs @@ -9,6 +9,10 @@ namespace SqlSugar.MongoDb /// public static class UtilExtensions { + public static bool IsInValues(this T thisValue, params T[] values) + { + return values.Contains(thisValue); + } public static string ObjToStringNoTrim(this object thisValue) { if (thisValue != null) return thisValue.ToString(); diff --git a/Src/Asp.NetCore2/SqlSugar.MongoDbCore/Tools/UtilMethods.cs b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/Tools/UtilMethods.cs index 8c9e9cc16..f57abef5c 100644 --- a/Src/Asp.NetCore2/SqlSugar.MongoDbCore/Tools/UtilMethods.cs +++ b/Src/Asp.NetCore2/SqlSugar.MongoDbCore/Tools/UtilMethods.cs @@ -10,12 +10,19 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; -using System.Text.RegularExpressions; +using System.Text.RegularExpressions; namespace SqlSugar.MongoDb { public class UtilMethods { + internal static MongoDB.Bson.IO.JsonWriterSettings GetJsonWriterSettings() + { + return new MongoDB.Bson.IO.JsonWriterSettings + { + OutputMode = MongoDB.Bson.IO.JsonOutputMode.Shell // JSON标准格式,带双引号 + }; + } internal static DateTime GetMinDate(ConnectionConfig currentConnectionConfig) { if (currentConnectionConfig.MoreSettings == null)