0

I'm trying to performing OrderBy decimal property on Mongo DB collection using C# mongo driver. Since the decimal is storing has string, I am not able to achieve this. How can I perform the OrderBy on decimal property?

//In the model

public decimal PayAmount { get; set; }

//While creating a query

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();

1 Answers1

0

Try this

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

But really I found you need to write a custom serializer for decimal there are some examples around if you search for serializing decimal in mongo.

This is not tested and you might need to write a custom serializer for decimal as mentioned.

AliK
  • 962
  • 2
  • 10
  • 31
  • query = query.OrderByDescending(x => Convert.ToDecimal(x.PayAmount)); Throws exception error as "Only fields are allowed in a $sort." from "MongoDB.Driver" – Pallavi Gowda Sep 09 '19 at 05:48
  • Out of interest why are you storing it as string? – AliK Sep 09 '19 at 06:05
  • In refference to this link https://stackoverflow.com/questions/24772173/linq-order-by-decimal-field-sorts-like-a-string I undersatnd that decimal values are stored as string in mongo db. – Pallavi Gowda Sep 09 '19 at 06:12
  • Are you using POCO to store your object. I would have the property set as decimal I used it a while back and the drive did take care of the conversion. As the link you refer to is very outdated and new features have been added to the driver. – AliK Sep 09 '19 at 07:03
  • No i am not using POCO..I am able to achieve the order by on making the changes to my model and DB as this [BsonRepresentation(BsonType.Decimal128)] public decimal PayAmount { get; set; }. But the problem with this is on QA or Production, we are using Azure cosmos DB ... after the above model change, i am getting error on query as "Command aggregate failed: 'Decimal128' is not supported." .... Since using C# Mongo db driver over Cosmos Db. Any help on the same. – Pallavi Gowda Sep 10 '19 at 09:50
  • I see I have not had much experience with Cosmos so maybe someone can advise. – AliK Sep 11 '19 at 04:29