Skip to content

CSHARP-5672: Support sorting by value in PushEach operation #1748

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
15 changes: 1 addition & 14 deletions src/MongoDB.Driver/IndexKeysDefinitionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -487,20 +487,7 @@ public override BsonDocument Render(RenderArgs<TDocument> args)
{
var renderedField = _field.Render(args);

BsonValue value;
switch (_direction)
{
case SortDirection.Ascending:
value = 1;
break;
case SortDirection.Descending:
value = -1;
break;
default:
throw new InvalidOperationException("Unknown value for " + typeof(SortDirection) + ".");
}

return new BsonDocument(renderedField.FieldName, value);
return new BsonDocument(renderedField.FieldName, _direction.Render());
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/MongoDB.Driver/SortDefinition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ public abstract class SortDefinition<TDocument>
/// <returns>A <see cref="BsonDocument"/>.</returns>
public abstract BsonDocument Render(RenderArgs<TDocument> args);

// TODO: remove this and refactor Render to return a BsonValue in 4.0
internal virtual BsonValue RenderAsBsonValue(RenderArgs<TDocument> args) => Render(args);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The RenderAsBsonValue method should probably be placed after the Render method.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It already is? Maybe you got a defective diff

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tagged the wrong one. It's the one on line 311 of SortDefinitionBuilder.cs that's out of order.


/// <summary>
/// Performs an implicit conversion from <see cref="BsonDocument"/> to <see cref="SortDefinition{TDocument}"/>.
/// </summary>
Expand Down
54 changes: 41 additions & 13 deletions src/MongoDB.Driver/SortDefinitionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,15 @@ public static SortDefinition<TDocument> MetaTextScore<TDocument>(this SortDefini
/// <typeparam name="TDocument">The type of the document.</typeparam>
public sealed class SortDefinitionBuilder<TDocument>
{
/// <summary>
/// Creates a value ascending sort.
/// </summary>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am wondering if should add a short example of what "value sort" is. As it might be not that evident to our users.
Something like "used for expressions that are not requiring a field, for example "$sort: -1"
cc @rstam

/// <returns>A value ascending sort.</returns>
public SortDefinition<TDocument> Ascending()
{
return new ValueDirectionalSortDefinition<TDocument>(SortDirection.Ascending);
}

/// <summary>
/// Creates an ascending sort.
/// </summary>
Expand Down Expand Up @@ -170,6 +179,15 @@ public SortDefinition<TDocument> Combine(IEnumerable<SortDefinition<TDocument>>
return new CombinedSortDefinition<TDocument>(sorts);
}

/// <summary>
/// Creates a value descending sort.
/// </summary>
/// <returns>A value descending sort.</returns>
public SortDefinition<TDocument> Descending()
{
return new ValueDirectionalSortDefinition<TDocument>(SortDirection.Descending);
}

/// <summary>
/// Creates a descending sort.
/// </summary>
Expand Down Expand Up @@ -232,6 +250,11 @@ internal sealed class CombinedSortDefinition<TDocument> : SortDefinition<TDocume
public CombinedSortDefinition(IEnumerable<SortDefinition<TDocument>> sorts)
{
_sorts = Ensure.IsNotNull(sorts, nameof(sorts)).ToList();

if (_sorts.Any(sort => sort is ValueDirectionalSortDefinition<TDocument>))
{
throw new InvalidOperationException("Value-based sort cannot be combined with other sorts. When sorting by the entire element value, no other sorting criteria can be applied.");
}
}

public override BsonDocument Render(RenderArgs<TDocument> args)
Expand Down Expand Up @@ -272,20 +295,25 @@ public override BsonDocument Render(RenderArgs<TDocument> args)
{
var renderedField = _field.Render(args);

BsonValue value;
switch (_direction)
{
case SortDirection.Ascending:
value = 1;
break;
case SortDirection.Descending:
value = -1;
break;
default:
throw new InvalidOperationException("Unknown value for " + typeof(SortDirection) + ".");
}
return new BsonDocument(renderedField.FieldName, _direction.Render());
}
}

return new BsonDocument(renderedField.FieldName, value);
internal sealed class ValueDirectionalSortDefinition<TDocument> : SortDefinition<TDocument>
{
private readonly SortDirection _direction;

public ValueDirectionalSortDefinition(SortDirection direction)
{
_direction = direction;
}

public override BsonDocument Render(RenderArgs<TDocument> args)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For now, I'm using the exception thrown during rendering as the mechanism to inform users that value-based sorts aren't supported. Since I've only updated call sites where value-based sorts are explicitly supported, any Render call that returns a BsonDocument will naturally fail in unsupported contexts, keeping this PR's changes minimal. However, Alex raised a point that when we update Render to return BsonValue in 4.0, we'll need to add validation at all call sites to check for value-based sort support before rendering. The question is whether to implement this validation now or defer it to 4.0. Implementing it now would distribute some of the 4.0 migration work and provide users with cleaner exceptions higher in the stack trace (and potentially a better exception type). I suppose we'll probably want to do that but what's the preference? @BorisDog @rstam

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the way you have it now is fine.

We can address whatever changes (if any) are needed later.

Most places that currently call Render should work with a BsonValue also. If not there is some work to be done a the CALL site, not here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @rstam, we can defer the work to 4.0.

{
throw new InvalidOperationException(
"Value-based sort cannot be rendered as a document. You might be trying to use a value-based sort where a field-based sort is expected.");
}

internal override BsonValue RenderAsBsonValue(RenderArgs<TDocument> args) => _direction.Render();
}
}
31 changes: 31 additions & 0 deletions src/MongoDB.Driver/SortDirectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using MongoDB.Bson;

namespace MongoDB.Driver
{
internal static class SortDirectionExtensions
{
internal static BsonValue Render(this SortDirection direction) =>
direction switch
{
SortDirection.Ascending => 1,
SortDirection.Descending => -1,
_ => throw new InvalidOperationException($"Invalid sort direction: {direction}.")
};
}
}
2 changes: 1 addition & 1 deletion src/MongoDB.Driver/UpdateDefinitionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1685,7 +1685,7 @@ public override BsonValue Render(RenderArgs<TDocument> args)

if (_sort != null)
{
document["$push"][renderedField.FieldName]["$sort"] = _sort.Render(args.WithNewDocumentType((IBsonSerializer<TItem>)itemSerializer));
document["$push"][renderedField.FieldName]["$sort"] = _sort.RenderAsBsonValue(args.WithNewDocumentType((IBsonSerializer<TItem>)itemSerializer));
}

return document;
Expand Down
39 changes: 38 additions & 1 deletion tests/MongoDB.Driver.Tests/SortDefinitionBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* limitations under the License.
*/

using System;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
Expand All @@ -31,6 +32,14 @@ public void Ascending()
Assert(subject.Ascending("a"), "{a: 1}");
}

[Fact]
public void Ascending_value()
{
var subject = CreateSubject<BsonDocument>();

Assert(subject.Ascending(), "1");
}

[Fact]
public void Ascending_Typed()
{
Expand Down Expand Up @@ -76,6 +85,16 @@ public void Combine_with_repeated_fields_using_extension_methods()
Assert(sort, "{b: -1, a: -1}");
}

[Fact]
public void Combine_with_value_based_sort_and_additional_sort_should_throw()
{
var subject = CreateSubject<BsonDocument>();

var exception = Record.Exception(() => subject.Ascending().Descending("b"));

exception.Should().BeOfType<InvalidOperationException>();
}

[Fact]
public void Descending()
{
Expand All @@ -84,6 +103,14 @@ public void Descending()
Assert(subject.Descending("a"), "{a: -1}");
}

[Fact]
public void Descending_value()
{
var subject = CreateSubject<BsonDocument>();

Assert(subject.Descending(), "-1");
}

[Fact]
public void Descending_Typed()
{
Expand Down Expand Up @@ -117,10 +144,20 @@ public void MetaTextScore()
Assert(subject.MetaTextScore("awesome"), "{awesome: {$meta: 'textScore'}}");
}

[Fact]
public void CallingRenderOnValueBasedSortShouldThrow()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use the underscores naming styling, like you did in
Combine_with_value_based_sort_and_additional_sort_should_throw

{
var subject = CreateSubject<BsonDocument>();

var exception = Record.Exception(() => subject.Ascending().Render(new RenderArgs<BsonDocument>()));

exception.Should().BeOfType<InvalidOperationException>();
}

private void Assert<TDocument>(SortDefinition<TDocument> sort, string expectedJson)
{
var documentSerializer = BsonSerializer.SerializerRegistry.GetSerializer<TDocument>();
var renderedSort = sort.Render(new(documentSerializer, BsonSerializer.SerializerRegistry));
var renderedSort = sort.RenderAsBsonValue(new(documentSerializer, BsonSerializer.SerializerRegistry));

renderedSort.Should().Be(expectedJson);
}
Expand Down