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; }
}
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?
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:
[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()));
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.