[CSHARP-2487] Does string field definition should match model filed name or document field name? Created: 22/Jan/19  Updated: 27/Oct/23  Resolved: 28/Jan/19

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Mikhail Bolshakov Assignee: Robert Stam
Resolution: Works as Designed Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Hi.

FilterDefinitionBuilder could accept string as first parameter for all of their method. Like this: 

var filterDefinition = Builders<Employee>.Filter.Eq("fieldName", "someValue");

Does this field should match property name of my model or it should match field name from document?

My issue that filter definition renders inproper query for date field if provided field name string doesnt match my model property name exactly.

In following example "dateOfBirth" doesn't mapped to model field Employee.DateOfBirth

var filterDefinition = Builders<Employee>.Filter.Eq("dateOfBirth", "2019-01-16");
mongoFilterDefinition.Render(coll.DocumentSerializer, coll.Settings.SerializerRegistry) // returns { "dateOfBirth" : "2019-01-16" }

And this filter doesn't work.

But if we will provide field name like "DateOfBirth" it will be mapped:

var filterDefinition = Builders<Employee>.Filter.Eq("DateOfBirth", "2019-01-16");
mongoFilterDefinition.Render(coll.DocumentSerializer, coll.Settings.SerializerRegistry) // returns { "dateOfBirth" : ISODate("2019-01-16T00:00:00Z") }

I found a place where this behaviour could be changed but I'm not sure if it's a bug.



 Comments   
Comment by Robert Stam [ 28/Jan/19 ]

The field name you pass to Filter.Eq should match the name of the property in your C# class.

If you pass a field name to Filter.Eq that does not match any property of your C# class then Filter.Eq simply uses that field name verbatim and serializes the value using a serializer from the serializer registry.

I realize this might seem odd, but there are at least two reasons for this:

  1. When writing queries against collections of BsonDocument you need to be able to write queries against arbitrary field names
  2. For backward compatibility

So just be sure to match the name of your C# class exactly (i.e. use "DateOfBirth" instead of "dateOfBirth").

You could also consider using the type safe version of Filter.Eq:

var filter = Builders<Employee>.Filter.Eq(x => x.DateOfBirth, new DateTime(2019116000, DateTimeKind.Utc));

Generated at Wed Feb 07 21:42:41 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.