[c#] linq query generates as string instead of decimal/int value

I’m working with c# driver and have problem with simple linq expression.
My mapping class:

public class ProductMapping
    {
        [BsonId]
        public ObjectId Id { set; get; }
        [BsonElement("name")]
        public string Name { set; get; }
        [BsonElement("price")]
        public decimal Price { set; get; }
        [BsonElement("description")]
        public string Description { set; get; }
        [BsonElement("available")]
        public bool Available { set; get; }
    }

and my linq query:

database.GetCollection<ProductMapping>("products").Find(x => x.Available && x.Price > 900);

Don’t know why, but the value 900 is converted to string, hence query doesn’t return any result.
What’s the solution to this that I obviously don’t see?

image

MongoDB interprets any number (say 900), by default, as a double. I think you will need to specify explicitly that the data type is of type Decimal128.

Annotate the Price field [BsonRepresentation(BsonType.Decimal128)], to specify that the data is stored in the MongoDB database as type Decimal128.

When querying you can use the MongoDB.Bson.Decimal128 type to specify the filter’s value, by using one of he constructors.; for example, new Decimal128(900).



Updated:

I tried some code. I have a document in my collection as follows. It has a DecimalNumber field:

{ "_id" : ObjectId("608050e3e4251729e6fb4a9e"), "fld" : NumberDecimal("12.456") }

My class has the field defined as follows:

[BsonRepresentation(BsonType.Decimal128)]
public decimal fld { get; set; }

My query using the fld:

var filter = Builders<MyClass>.Filter.Eq("fld", new Decimal(12.456));
var list = collection.Find(filter).ToList<MyClass>();
list.ForEach(e => Console.WriteLine(e.ToJson()));

The query successfully retrieved the document:

{ "_id" : ObjectId("608050e3e4251729e6fb4a9e"), "fld" : NumberDecimal("12.456") }

Thank you for explanation. BsonRepresentation attribute was enought to get it to work.
I see I need to get more into mongo data types to fully understand what you provided.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.