Skip to content

Commit 384d10d

Browse files
onyxmasterDmitryLukyanov
authored andcommitted
CSHARP-2739: Improve hierarchical fields projection.
1 parent aa87ba9 commit 384d10d

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

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

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -218,12 +218,8 @@ private static IReadOnlyList<IFieldExpression> GetUniqueFieldsByHierarchy(IEnume
218218
var referenceGroup = referenceGroups.Dequeue();
219219
if (!skippedFields.Contains(referenceGroup.Key))
220220
{
221-
var hierarchicalReferenceGroups = referenceGroups
222-
.Where(x =>
223-
{
224-
return x.Key.Count(c => c == '.') != referenceGroup.Key.Count(c => c == '.') && // otherwise, fields are on the same nesting level
225-
x.Key.StartsWith(referenceGroup.Key);
226-
});
221+
var prefix = referenceGroup.Key + '.';
222+
var hierarchicalReferenceGroups = referenceGroups.Where(x => x.Key.StartsWith(prefix));
227223
uniqueFields.AddRange(referenceGroup);
228224
skippedFields.AddRange(hierarchicalReferenceGroups.Select(x => x.Key));
229225
}

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,17 @@ public void Should_translate_with_a_hierarchical_redundancy_and_a_top_level_proj
192192
result.Value.F.Should().Be(2);
193193
}
194194

195+
[Fact]
196+
public void Should_translate_with_a_hierarchical_redundancy_and_when_one_field_doesnt_start_with_another()
197+
{
198+
var result = Project(p => new { p.C.E, F = p.C.E1.F }, "{ C : { E : { H : 3 }, E1 : { F : 2 } } }");
199+
200+
result.Projection.Should().Be("{ \"C.E\" : 1, \"C.E1.F\" : 1, _id : 0 }");
201+
202+
result.Value.E.H.Should().Be(3);
203+
result.Value.F.Should().Be(2);
204+
}
205+
195206
[Fact]
196207
public void Should_translate_with_a_hierarchical_redundancy_and_when_one_field_starts_with_another()
197208
{

0 commit comments

Comments
 (0)