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

Issue with find_one_and_update when including sort key and excluding _id #904

Open
val500 opened this issue Oct 16, 2024 · 1 comment
Open

Comments

@val500
Copy link

val500 commented Oct 16, 2024

When including a sort key to the find_one_and_update function, while excluding the "_id" with a projection, find_one_and_update will find the document with sorting, but will update a different document. Here's a short script to demonstrate this behavior:

import mongomock


class MongoClientMock(mongomock.MongoClient):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def start_session(self, *args, **kwargs):
        return super().start_session(*args, **kwargs)


def without_id():
    print("without id")
    mock_mongo = MongoClientMock()
    mock_mongo.db.my_collection.insert_one(
        {"field1": "mydata", "field2": 10},
    )
    mock_mongo.db.my_collection.insert_one(
        {"field1": "mydata", "field2": 20},
    )

    # This is the document that is found with this query
    found_response = mock_mongo.db.my_collection.find_one_and_update(
        {"field1": "mydata"},
        {"$set": {"field1": "mynewdata"}},
        projection={
            "_id": False,
        },
        sort=[("field2", -1)],
    )
    print(found_response)

    # This is the document that was updated by the previous query
    updated_response = mock_mongo.db.my_collection.find_one(
        {"field1": "mynewdata"}
    )
    print(updated_response)
    # These documents should be the same but are different


def with_id():
    print("with id")
    mock_mongo = MongoClientMock()
    mock_mongo.db.my_collection.insert_one(
        {"field1": "mydata", "field2": 10},
    )
    mock_mongo.db.my_collection.insert_one(
        {"field1": "mydata", "field2": 20},
    )
    found_response = mock_mongo.db.my_collection.find_one_and_update(
        {"field1": "mydata"},
        {"$set": {"field1": "mynewdata"}},
        sort=[("field2", -1)],
    )
    print(found_response)

    updated_response = mock_mongo.db.my_collection.find_one(
        {"field1": "mynewdata"}
    )
    print(updated_response)
    # These documents are the same as expected when _id is included


if __name__ == "__main__":
    without_id()
    with_id()
@val500
Copy link
Author

val500 commented Oct 16, 2024

I believe it is because this query only gets reupdated if "_id" is found in that document:

if old and '_id' in old:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant