【问题标题】:OrderBy and OrderByDescending query on a decimal stored as a string [duplicate]OrderBy 和 OrderByDescending 查询存储为字符串的小数 [重复]
【发布时间】:2019-09-09 05:07:36
【问题描述】:

我正在尝试使用 C# mongo 驱动程序对 Mongo DB 集合执行 OrderBy 十进制属性。由于十进制存储有字符串,我无法实现这一点。如何对小数属性执行 OrderBy?

//在模型中

public decimal PayAmount { get; set; }

//创建查询时

var predicate = PredicateBuilder.New<Documents.Job>();
predicate = predicate.And(x => x.Status == jobStatus);
var jobdata = context.Jobs.AsQueryable().Where(predicate);
var query = from a in jobdata  select new { //selects Field here  };
query = query.OrderByDescending(x => x.PayAmount); // this does not sort and PayAmount is decimal type
var jobs = await query.ToListAsync();

【问题讨论】:

  • 你能更新完整的查询吗?

标签: c# mongodb linq mongodb-query


【解决方案1】:

试试这个

query.OrderByDescending(x => Convert.ToDecimal(x.PayAmount));

但实际上,我发现您需要为小数编写自定义序列化程序,如果您在 mongo 中搜索序列化小数,则有一些示例。

这未经测试,您可能需要为小数编写自定义序列化程序,如上所述。

【讨论】:

  • query = query.OrderByDescending(x => Convert.ToDecimal(x.PayAmount));抛出异常错误,因为“$sort 中只允许使用字段”。来自“MongoDB.Driver”
  • 出于兴趣,为什么将其存储为字符串?
  • 参考这个链接stackoverflow.com/questions/24772173/…我undersatnd十进制值作为字符串存储在mongo db中。
  • 您是否使用 POCO 来存储您的对象。我会将属性设置为十进制,我不久前使用过它,驱动器确实负责转换。由于您引用的链接非常过时,并且已将新功能添加到驱动程序中。
  • 不,我没有使用 POCO ..我可以通过更改我的模型和数据库来实现订单 [BsonRepresentation(BsonType.Decimal128)] public decimal PayAmount { get;放; }。但问题出在 QA 或生产上,我们使用的是 Azure cosmos DB ...在上述模型更改后,我在查询时遇到错误,因为“命令聚合失败:不支持‘Decimal128’。” .... 由于在 Cosmos Db 上使用 C# Mongo db 驱动程序。任何帮助。
猜你喜欢
  • 1970-01-01
  • 2019-12-21
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 2021-02-26
  • 1970-01-01
  • 2012-08-28
相关资源
最近更新 更多