Skip to content

Commit 79853e2

Browse files
craiggwilsonrstam
authored andcommitted
CSHARP-1623: add support for $dateToString.
1 parent 2d02931 commit 79853e2

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/MongoDB.Driver/Linq/Translators/AggregateLanguageTranslator.cs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,12 @@ private BsonValue TranslateMethodCall(MethodCallExpression node)
366366
return result;
367367
}
368368

369+
if (node.Object.Type == typeof(DateTime)
370+
&& TryTranslateDateTimeCall(node, out result))
371+
{
372+
return result;
373+
}
374+
369375
if (node.Object.Type.GetTypeInfo().IsGenericType
370376
&& node.Object.Type.GetGenericTypeDefinition() == typeof(HashSet<>)
371377
&& TryTranslateHashSetMethodCall(node, out result))
@@ -672,6 +678,29 @@ private bool TryTranslateCountResultOperator(PipelineExpression node, out BsonVa
672678
return false;
673679
}
674680

681+
private bool TryTranslateDateTimeCall(MethodCallExpression node, out BsonValue result)
682+
{
683+
result = null;
684+
var field = TranslateValue(node.Object);
685+
686+
switch (node.Method.Name)
687+
{
688+
case "ToString":
689+
if (node.Arguments.Count == 1)
690+
{
691+
var format = TranslateValue(node.Arguments[0]);
692+
result = new BsonDocument("$dateToString", new BsonDocument
693+
{
694+
{ "format", format },
695+
{ "date", field }
696+
});
697+
}
698+
return true;
699+
}
700+
701+
return false;
702+
}
703+
675704
private bool TryTranslateDateTimeMemberAccess(MemberExpression node, out BsonValue result)
676705
{
677706
result = null;

tests/MongoDB.Driver.Tests/Linq/Translators/AggregateProjectTranslatorTests.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,18 @@ public void Should_translate_condition()
412412
result.Value.Result.Should().Be("b");
413413
}
414414

415+
[SkippableFact]
416+
public void Should_translate_dateToString()
417+
{
418+
RequireServer.Where(minimumVersion: "3.2.0");
419+
420+
var result = Project(x => new { Result = x.J.ToString("%Y-%m-%d") });
421+
422+
result.Projection.Should().Be("{ Result: { \"$dateToString\": {format: \"%Y-%m-%d\", date: \"$J\" } }, _id: 0 }");
423+
424+
result.Value.Result.Should().Be("2012-12-01");
425+
}
426+
415427
[Fact]
416428
public void Should_translate_day_of_month()
417429
{

0 commit comments

Comments
 (0)