Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/MongoDB.Driver/ProjectionDefinitionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -789,7 +789,18 @@ internal sealed class CombinedProjectionDefinition<TSource> : ProjectionDefiniti

public CombinedProjectionDefinition(IEnumerable<ProjectionDefinition<TSource>> projections)
{
_projections = Ensure.IsNotNull(projections, nameof(projections)).ToList();
// Unwind CombinedProjectionDefinitions to avoid deep recursion on Render
_projections = Ensure.IsNotNull(projections, nameof(projections))
.Aggregate(new List<ProjectionDefinition<TSource>>(), (current, projection) =>
{
if (projection is CombinedProjectionDefinition<TSource> combinedProjection)
{
current.AddRange(combinedProjection._projections);
} else
current.Add(projection);
return current;
})
.ToList();
}

public override BsonDocument Render(IBsonSerializer<TSource> sourceSerializer, IBsonSerializerRegistry serializerRegistry, LinqProvider linqProvider)
Expand Down
19 changes: 19 additions & 0 deletions tests/MongoDB.Driver.Tests/ProjectionDefinitionBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*/

using System.Linq;
using System.Text;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
Expand Down Expand Up @@ -61,6 +62,24 @@ public void Combine_with_redundant_fields_using_extension_method()
Assert(projection, "{LastName: 0, fn: 1}");
}

[Fact]
public void Combine_many_fields_should_not_overflow_stack_on_Render()
{
var subject = CreateSubject<Person>();

var projection = subject.Include(x => x.FirstName);
var expectedProjection = new StringBuilder("{fn: 1");
for (int i = 0; i < 10000; i++)
{
var field = $"Field{i}";
projection = projection.Include(field);
expectedProjection.Append($", {field}: 1");
}
expectedProjection.Append("}");

Assert(projection, expectedProjection.ToString());
}

[Fact]
public void ElemMatch()
{
Expand Down