Update mongodb

This commit is contained in:
sunkaixuan 2025-05-06 19:43:40 +08:00
parent ee1799769a
commit 3c46dde2a4
4 changed files with 33 additions and 3 deletions

View File

@ -65,6 +65,7 @@ namespace MongoDb.Ado.data
return typeof(string); return typeof(string);
} }
if (obj == null) return typeof(object); if (obj == null) return typeof(object);
if (obj is BsonNull) return typeof(object);
return BsonTypeMapper.MapToDotNetValue(obj).GetType(); return BsonTypeMapper.MapToDotNetValue(obj).GetType();
} }
public override float GetFloat(int ordinal) => (float)GetValue(ordinal); public override float GetFloat(int ordinal) => (float)GetValue(ordinal);

View File

@ -37,6 +37,8 @@ namespace MongoDbTest
var list3= db.Queryable<OrderInfo>().Skip(1).Take(1).ToList(); var list3= db.Queryable<OrderInfo>().Skip(1).Take(1).ToList();
var list4 = db.Queryable<OrderInfo>().OrderByDescending(it=>it.Price).ToList();
//测试生成SQL性能 //测试生成SQL性能
TestSqlBuilder(db); TestSqlBuilder(db);
} }

View File

@ -11,7 +11,12 @@ namespace SqlSugar.MongoDbCore
{ {
public static BsonDocument Translate(Expression expr, MongoNestedTranslatorContext context) public static BsonDocument Translate(Expression expr, MongoNestedTranslatorContext context)
{ {
return (BsonDocument)new ExpressionVisitor(context).Visit(expr); var result = new ExpressionVisitor(context).Visit(expr);
if (result is BsonString bs)
{
result = new BsonDocument("fieldName", bs);
}
return (BsonDocument)result;
} }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using MongoDB.Bson;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -77,7 +78,28 @@ namespace SqlSugar.MongoDb
if (this.Take.HasValue) if (this.Take.HasValue)
{ {
operations.Add($"{{ \"$limit\": {this.Take.Value} }}"); operations.Add($"{{ \"$limit\": {this.Take.Value} }}");
} }
#endregion
#region OrderBy
var order = this.GetOrderByString;
var orderByString = this.GetOrderByString?.Trim();
if (!string.IsNullOrEmpty(orderByString) && orderByString.StartsWith("ORDER BY ", StringComparison.OrdinalIgnoreCase))
{
order = order.Substring("ORDER BY ".Length).Trim();
int lastSpace = order.LastIndexOf(' ');
string jsonPart = order.Substring(0, lastSpace).Trim();
string directionPart = order.Substring(lastSpace + 1).Trim().ToUpper();
var bson = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonPart);
if (bson.Contains("fieldName"))
{
var field = bson["fieldName"].AsString;
var direction = directionPart == "ASC" ? 1 : -1;
operations.Add($"{{ \"$sort\": {{ \"{field}\": {direction} }} }}");
}
}
#endregion #endregion
sb.Append($"aggregate {this.GetTableNameString} "); sb.Append($"aggregate {this.GetTableNameString} ");