Skip to content
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

Allow updateOne and replaceOne to supply sort option #1585

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.mongodb.client.model;

import com.mongodb.lang.Nullable;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.BsonValue;
import org.bson.conversions.Bson;
Expand All @@ -31,6 +32,7 @@ public final class BulkWriteOptions {
private Boolean bypassDocumentValidation;
private BsonValue comment;
private Bson variables;
private BsonDocument sort;
Copy link
Member

Choose a reason for hiding this comment

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

Judging by the spec, BulkWriteOptions does not seem to require a sort option.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I overlooked that part, will remove it!


/**
* If true, then when a write fails, return without performing the remaining
Expand Down Expand Up @@ -147,13 +149,40 @@ public BulkWriteOptions let(@Nullable final Bson variables) {
return this;
}

/**
* Gets the sort criteria to apply to the query. The default is null, which means that the documents will be returned in an undefined
* order.
*
* @return a document describing the sort criteria
* @since 5.3
* @mongodb.driver.manual reference/method/cursor.sort/ Sort
*/
@Nullable
public BsonDocument getSort() {
return sort;
}

/**
* Sets the sort criteria to apply to the query.
*
* @param sort the sort criteria, which may be null.
* @return this
* @since 5.3
* @mongodb.driver.manual reference/method/cursor.sort/ Sort
*/
public BulkWriteOptions sort(@Nullable final BsonDocument sort) {
this.sort = sort;
return this;
}

@Override
public String toString() {
return "BulkWriteOptions{"
+ "ordered=" + ordered
+ ", bypassDocumentValidation=" + bypassDocumentValidation
+ ", comment=" + comment
+ ", let=" + variables
+ ", sort=" + sort
+ '}';
}
}
29 changes: 29 additions & 0 deletions driver-core/src/main/com/mongodb/client/model/UpdateOptions.java
Copy link
Member

Choose a reason for hiding this comment

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

Let’s also add unit tests to UpdateOptionsSpecification and UpdateRequestSpecification.

Additionally, we should update the tests in MongoCollectionSpecification to cover the logic for the new option.

Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.mongodb.lang.Nullable;
import org.bson.BsonString;
import org.bson.BsonValue;
import org.bson.BsonDocument;
import org.bson.conversions.Bson;

import java.util.List;
Expand All @@ -40,6 +41,7 @@ public class UpdateOptions {
private String hintString;
private BsonValue comment;
private Bson variables;
private BsonDocument sort;
Copy link
Member

Choose a reason for hiding this comment

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

Let’s use the Bson type here to allow users to choose between Document and BsonDocument, similar to how it’s done in FindOneAndDeleteOptions and other cases.


/**
* Returns true if a new document should be inserted if there are no matches to the query filter. The default is false.
Expand Down Expand Up @@ -256,6 +258,32 @@ public UpdateOptions let(final Bson variables) {
return this;
}

/**
* Gets the sort criteria to apply to the query. The default is null, which means that the documents will be returned in an undefined
* order.
*
* @return a document describing the sort criteria
* @since 5.3
* @mongodb.driver.manual reference/method/cursor.sort/ Sort
Copy link
Member

Choose a reason for hiding this comment

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

Should we remove the manual reference here and from the getSort method, given that it seems more relevant to the cursor?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I referenced the findOptions and the other findOneAnd..Options and thought it might be helpful to have a reference! I don't have a strong opinion here though.

*/
@Nullable
public BsonDocument getSort() {
return sort;
}

/**
* Sets the sort criteria to apply to the query.
*
Copy link
Member

Choose a reason for hiding this comment

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

Could we clarify the purpose of this sort option in the Javadoc? It would be helpful to explain how it determines which document is updated when multiple matches are found.

Suggested change
*
*
* When multiple documents match the query, the sort order specifies the document
* to be updated first.
*

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Will do!

* @param sort the sort criteria, which may be null.
* @return this
* @since 5.3
* @mongodb.driver.manual reference/method/cursor.sort/ Sort
*/
public UpdateOptions sort(@Nullable final BsonDocument sort) {
Copy link
Member

@vbabanin vbabanin Dec 19, 2024

Choose a reason for hiding this comment

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

Should we consider adding a note in the Javadoc to clarify that sort is not applicable to updateMany? This could help avoid confusion for users.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is a good point, will go ahead and add it!

this.sort = sort;
return this;
}

@Override
public String toString() {
return "UpdateOptions{"
Expand All @@ -267,6 +295,7 @@ public String toString() {
+ ", hintString=" + hintString
+ ", comment=" + comment
+ ", let=" + variables
+ ", sort=" + sort
+ '}';
}
}
11 changes: 11 additions & 0 deletions driver-core/src/main/com/mongodb/internal/bulk/UpdateRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public final class UpdateRequest extends WriteRequest {
private List<BsonDocument> arrayFilters;
@Nullable private BsonDocument hint;
@Nullable private String hintString;
@Nullable private BsonDocument sort;

public UpdateRequest(final BsonDocument filter, @Nullable final BsonValue update, final Type updateType) {
if (updateType != Type.UPDATE && updateType != Type.REPLACE) {
Expand Down Expand Up @@ -128,5 +129,15 @@ public UpdateRequest hintString(@Nullable final String hint) {
this.hintString = hint;
return this;
}

@Nullable
public BsonDocument getSort() {
return sort;
}

public UpdateRequest sort(@Nullable final BsonDocument sort) {
this.sort = sort;
return this;
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,11 @@ public void encode(final BsonWriter writer, final WriteRequestWithIndex writeReq
} else if (update.getHintString() != null) {
writer.writeString("hint", update.getHintString());
}
if (update.getSort() != null) {
writer.writeName("sort");
getCodec(assertNotNull(update.getSort())).encode(writer, assertNotNull(update.getSort()),
EncoderContext.builder().build());
}
writer.writeEndDocument();
} else {
DeleteRequest deleteRequest = (DeleteRequest) writeRequestWithIndex.getWriteRequest();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ public class MixedBulkWriteOperation implements AsyncWriteOperation<BulkWriteRes
private Boolean bypassDocumentValidation;
private BsonValue comment;
private BsonDocument variables;
private BsonDocument sort;

public MixedBulkWriteOperation(final MongoNamespace namespace, final List<? extends WriteRequest> writeRequests,
final boolean ordered, final WriteConcern writeConcern, final boolean retryWrites) {
Expand Down Expand Up @@ -130,6 +131,15 @@ public MixedBulkWriteOperation comment(@Nullable final BsonValue comment) {
return this;
}

public BsonDocument getSort() {
return sort;
}

public MixedBulkWriteOperation sort(@Nullable final BsonDocument sort) {
this.sort = sort;
return this;
}

Copy link
Member

@vbabanin vbabanin Dec 27, 2024

Choose a reason for hiding this comment

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

These methods don’t appear to be used. Should we consider removing them?

This also applies to ReplaceRequest.

public MixedBulkWriteOperation let(@Nullable final BsonDocument variables) {
this.variables = variables;
return this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -403,13 +403,13 @@ MixedBulkWriteOperation deleteMany(final Bson filter, final DeleteOptions option
MixedBulkWriteOperation updateOne(final Bson filter, final Bson update, final UpdateOptions options) {
return bulkWrite(singletonList(new UpdateOneModel<>(filter, update, options)),
new BulkWriteOptions().bypassDocumentValidation(options.getBypassDocumentValidation())
.comment(options.getComment()).let(options.getLet()));
.comment(options.getComment()).let(options.getLet()).sort(options.getSort()));
}

MixedBulkWriteOperation updateOne(final Bson filter, final List<? extends Bson> update, final UpdateOptions options) {
return bulkWrite(singletonList(new UpdateOneModel<>(filter, update, options)),
new BulkWriteOptions().bypassDocumentValidation(options.getBypassDocumentValidation())
.comment(options.getComment()).let(options.getLet()));
.comment(options.getComment()).let(options.getLet()).sort(options.getSort()));
}

MixedBulkWriteOperation updateMany(final Bson filter, final Bson update, final UpdateOptions options) {
Expand Down Expand Up @@ -475,7 +475,8 @@ MixedBulkWriteOperation bulkWrite(final List<? extends WriteModel<? extends TDoc
.collation(updateOneModel.getOptions().getCollation())
.arrayFilters(toBsonDocumentList(updateOneModel.getOptions().getArrayFilters()))
.hint(toBsonDocument(updateOneModel.getOptions().getHint()))
.hintString(updateOneModel.getOptions().getHintString());
.hintString(updateOneModel.getOptions().getHintString())
.sort(updateOneModel.getOptions().getSort());
} else if (writeModel instanceof UpdateManyModel) {
UpdateManyModel<TDocument> updateManyModel = (UpdateManyModel<TDocument>) writeModel;
BsonValue update = updateManyModel.getUpdate() != null ? toBsonDocument(updateManyModel.getUpdate())
Expand Down Expand Up @@ -509,7 +510,8 @@ MixedBulkWriteOperation bulkWrite(final List<? extends WriteModel<? extends TDoc
options.isOrdered(), writeConcern, retryWrites)
.bypassDocumentValidation(options.getBypassDocumentValidation())
.comment(options.getComment())
.let(toBsonDocument(options.getLet()));
.let(toBsonDocument(options.getLet()))
.sort(options.getSort());
}

<TResult> CommandReadOperation<TResult> commandRead(final Bson command, final Class<TResult> resultClass) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1159,6 +1159,9 @@ private UpdateOptions getUpdateOptions(final BsonDocument arguments) {
case "collation":
options.collation(asCollation(cur.getValue().asDocument()));
break;
case "sort":
options.sort(cur.getValue().asDocument());
break;
default:
throw new UnsupportedOperationException("Unsupported argument: " + cur.getKey());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,8 @@ public static void doSkips(final TestDef def) {
.test("crud", "findOneAndDelete-hint-unacknowledged", "Unacknowledged findOneAndDelete with hint string on 4.4+ server")
.test("crud", "findOneAndDelete-hint-unacknowledged", "Unacknowledged findOneAndDelete with hint document on 4.4+ server");
def.skipJira("https://jira.mongodb.org/browse/JAVA-5622")
.test("crud", "updateOne-sort", "UpdateOne with sort option")
.test("crud", "updateOne-sort", "updateOne with sort option unsupported (server-side error)")
.test("crud", "replaceOne-sort", "ReplaceOne with sort option")
.test("crud", "replaceOne-sort", "replaceOne with sort option unsupported (server-side error)")
.test("crud", "BulkWrite updateOne-sort", "BulkWrite updateOne with sort option")
.test("crud", "BulkWrite updateOne-sort", "BulkWrite updateOne with sort option unsupported (server-side error)")
.test("crud", "BulkWrite replaceOne-sort", "BulkWrite replaceOne with sort option")
.test("crud", "BulkWrite replaceOne-sort", "BulkWrite replaceOne with sort option unsupported (server-side error)");

Expand Down