Update mongodb

This commit is contained in:
sunkaixuan
2025-05-08 20:02:51 +08:00
parent 13e3305ee5
commit cde25a6417
7 changed files with 127 additions and 14 deletions

View File

@@ -22,13 +22,28 @@ namespace MongoDbTest
.ExecuteReturnPkList<string>();
var updateRow = db.Updateable(new List<OrderInfo>()
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<OrderInfo>()
{
new OrderInfo() { Id = ids.First(),Name="a31",Price=11},
new OrderInfo() { Id = ids.Last(),Name="a41"}
})
.ExecuteCommand();
var updateRow3= db.Updateable<OrderInfo>()
.SetColumns(it=>it.Name=="aa")
.Where(it=>it.Id==ids.Last())
.ExecuteCommand();
var delrow = db.Deleteable(new OrderInfo() { Id = ids.Last() })
.ExecuteCommand();

View File

@@ -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}");
}

View File

@@ -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;
}
}
}

View File

@@ -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<string>();
List<string> pks = this.PrimaryKeys;
if (this.SetValues.Any())
{
var setOperation = new BsonDocument();
foreach (var item in this.SetValues)
{
var bson = BsonSerializer.Deserialize<BsonDocument>(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<IGrouping<int, DbColumnInfo>> groupList, List<string> operations, List<string> pks)
{
foreach (var group in groupList)
{
var filter = new BsonDocument();
@@ -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();
}
}
}
}

View File

@@ -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<T>:UpdateableProvider<T> where T:class,new()
{
public override IUpdateable<T> SetColumns(Expression<Func<T, bool>> 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<BsonDocument>(expResult);
foreach (var element in bson)
{
string key = element.Name;
BsonValue value = element.Value;
this.UpdateBuilder.SetValues.Add(new KeyValuePair<string, string>(key, expResult));
}
return this;
}
}
}

View File

@@ -9,6 +9,10 @@ namespace SqlSugar.MongoDb
/// </summary>
public static class UtilExtensions
{
public static bool IsInValues<T>(this T thisValue, params T[] values)
{
return values.Contains(thisValue);
}
public static string ObjToStringNoTrim(this object thisValue)
{
if (thisValue != null) return thisValue.ToString();

View File

@@ -16,6 +16,13 @@ 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)