Is there a way to get a nullable value from a MongoDB C# driver projection with expression?

Viewed 27

Lets say I have these classes:

public class Foo
{
   public DateTime Value { get; set; }
}

public class Bar
{
   public Foo? Foo { get; set; }
}

Now if I do this projection:

var projection = Builders<Bar>.Projection.Expression(x => x.Foo!.Value)

I will get DateTime.MinValue and not a null in case Foo is null. The Value itself indeed cannot be null (and I assume that is why MongoDB is doing default(DateTime)), but the path to Value can be.

I am wondering if there is a good way to tell MongoDB that the result should be DateTime? so that I can get a null in case Foo does not exist.

P.S. I can make the Value DateTime?, and that will work but I would rather avoid it, since the Value itself should not ever be null.

1 Answers

The following query returns the values as DateTime?; if there is no Foo, it is null, if it is set, it returns the value:

var bars = await (await barColl.FindAsync(
  Builders<Bar>.Filter.Empty, 
  new FindOptions<Bar, DateTime?>()
  {
    Projection = Builders<Bar>.Projection.Expression(
      x => (DateTime?) (x.Foo == null ? null : x.Foo.Value))
  })).ToListAsync();

For the following documents

{ "_id": { "$oid": "632dc047e08f08bfaeabc2d6" }, "Foo": null}
{ "_id": { "$oid": "632dc047e08f08bfaeabc2d7" }, "Foo": { "Value": { "$date": {  "$numberLong": "1663942727428" } } }}

the result is

null
2022-09-23T14:18:47Z
Related