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 4 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
29 changes: 29 additions & 0 deletions driver-core/src/main/com/mongodb/client/model/ReplaceOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public class ReplaceOptions {
private String hintString;
private BsonValue comment;
private Bson variables;
private Bson sort;

/**
* 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 @@ -221,6 +222,33 @@ public ReplaceOptions 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/db.collection.replaceOne/ Sort
*/
Copy link
Member

Choose a reason for hiding this comment

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

The sort criteria in the replace operation determines the order in which matching documents are processed. It does not return documents to the caller unless it’s used in a specific operation like findAndModify.

We should also specify the minimum server version @mongodb.server.release 8.0 for this option.

Should we clarify this in the Javadoc? Here’s a suggestion to make this more explicit:

Suggested change
/**
* 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/db.collection.replaceOne/ Sort
*/
/**
* Gets the sort criteria to apply to the operation.
*
* <p>
* The sort criteria determines which document the operation replaces if the query matches multiple documents.
* The first document matched by the sort criteria will be replaced.
* The default is null, which means no specific sort criteria is applied.
*
* @return a document describing the sort criteria, or null if no sort is specified.
* @mongodb.driver.manual reference/method/db.collection.replaceOne/ Sort
* @mongodb.server.release 8.0
* @since 5.3
* @see #sort(Bson)
*/

If the ReplaceOptions.getSort() method Javadoc gets updated, we should make similar changes to the equivalent UpdateOptions method for consistency.

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

/**
* Sets the sort criteria to apply to the query. When multiple documents match the query, the sort order specifies the document to be
* updated first.
*
* @param sort the sort criteria, which may be null.
* @return this
* @since 5.3
* @mongodb.driver.manual reference/method/db.collection.replaceOne/ Sort
*/
Copy link
Member

Choose a reason for hiding this comment

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

The term replaces might be more appropriate than updates here, as this operation replaces the entire document.

We should also specify the minimum server version that supports this option.

What do you think about updating the Javadoc to something like this?

Suggested change
/**
* Sets the sort criteria to apply to the query. When multiple documents match the query, the sort order specifies the document to be
* updated first.
*
* @param sort the sort criteria, which may be null.
* @return this
* @since 5.3
* @mongodb.driver.manual reference/method/db.collection.replaceOne/ Sort
*/
/**
* Sets the sort criteria to apply to the operation. A null value means no sort criteria is set.
*
* <p>
* The sort criteria determines which document the operation replaces if the query matches multiple documents.
* The first document matched by the specified sort criteria will be replaced.
*
* @param sort the sort criteria, which may be null.
* @return this
* @mongodb.driver.manual reference/method/db.collection.replaceOne/ Sort
* @mongodb.server.release 8.0
* @since 5.3
*/

If the ReplaceOptions.sort() method Javadoc gets updated, we should make similar changes to the equivalent UpdateOptions method for consistency.

public ReplaceOptions sort(@Nullable final Bson sort) {
this.sort = sort;
return this;
}

@Override
public String toString() {
return "ReplaceOptions{"
Expand All @@ -231,6 +259,7 @@ public String toString() {
+ ", hintString=" + hintString
+ ", comment=" + comment
+ ", let=" + variables
+ ", sort=" + sort
+ '}';
}
}
31 changes: 31 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 @@ -40,6 +40,7 @@ public class UpdateOptions {
private String hintString;
private BsonValue comment;
private Bson variables;
private Bson sort;

/**
* 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 +257,35 @@ 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/db.collection.updateOne/ Sort
*/
@Nullable
public Bson getSort() {
return sort;
}

/**
* Sets the sort criteria to apply to the query. When multiple documents match the query, the sort order specifies the document to be
* updated first.
*
* <p>Note: The sort is not applicable to updateMany.</p>
*
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/db.collection.updateOne/ Sort
*/
public UpdateOptions sort(@Nullable final Bson sort) {
this.sort = sort;
return this;
}

@Override
public String toString() {
return "UpdateOptions{"
Expand All @@ -267,6 +297,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 @@ -464,7 +464,8 @@ MixedBulkWriteOperation bulkWrite(final List<? extends WriteModel<? extends TDoc
.upsert(replaceOneModel.getReplaceOptions().isUpsert())
.collation(replaceOneModel.getReplaceOptions().getCollation())
.hint(toBsonDocument(replaceOneModel.getReplaceOptions().getHint()))
.hintString(replaceOneModel.getReplaceOptions().getHintString());
.hintString(replaceOneModel.getReplaceOptions().getHintString())
.sort(toBsonDocument(replaceOneModel.getReplaceOptions().getSort()));
} else if (writeModel instanceof UpdateOneModel) {
UpdateOneModel<TDocument> updateOneModel = (UpdateOneModel<TDocument>) writeModel;
BsonValue update = updateOneModel.getUpdate() != null ? toBsonDocument(updateOneModel.getUpdate())
Expand All @@ -475,7 +476,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(toBsonDocument(updateOneModel.getOptions().getSort()));
} else if (writeModel instanceof UpdateManyModel) {
UpdateManyModel<TDocument> updateManyModel = (UpdateManyModel<TDocument>) writeModel;
BsonValue update = updateManyModel.getUpdate() != null ? toBsonDocument(updateManyModel.getUpdate())
Expand Down
18 changes: 16 additions & 2 deletions driver-legacy/src/main/com/mongodb/ReplaceRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

import com.mongodb.client.model.Collation;
import com.mongodb.internal.bulk.UpdateRequest;
import com.mongodb.lang.Nullable;
import org.bson.BsonDocument;
import org.bson.BsonDocumentWrapper;
import org.bson.codecs.Encoder;

Expand All @@ -28,6 +30,7 @@ class ReplaceRequest extends WriteRequest {
private final Encoder<DBObject> codec;
private final Encoder<DBObject> replacementCodec;
private final Collation collation;
@Nullable private BsonDocument sort;

ReplaceRequest(final DBObject query, final DBObject document, final boolean upsert, final Encoder<DBObject> codec,
final Encoder<DBObject> replacementCodec, final Collation collation) {
Expand Down Expand Up @@ -55,12 +58,23 @@ public Collation getCollation() {
return collation;
}

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

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

@Override
com.mongodb.internal.bulk.WriteRequest toNew(final DBCollection dbCollection) {
return new UpdateRequest(new BsonDocumentWrapper<>(query, codec),
new BsonDocumentWrapper<>(document, replacementCodec),
com.mongodb.internal.bulk.WriteRequest.Type.REPLACE)
.upsert(isUpsert())
.collation(getCollation());
.upsert(isUpsert())
.collation(getCollation())
.sort(getSort());
}
}
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 Expand Up @@ -1193,6 +1196,9 @@ private ReplaceOptions getReplaceOptions(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 @@ -135,15 +135,6 @@ public static void doSkips(final TestDef def) {
.test("crud", "findOneAndUpdate-hint-unacknowledged", "Unacknowledged findOneAndUpdate with hint document on 4.4+ server")
.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)");

// gridfs

Expand Down