8000 Issue with find_one_and_update when including sort key and excluding _id · Issue #904 · mongomock/mongomock · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Issue with find_one_and_update when including sort key and excluding _id #904
Open
@val500

Description

@val500

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()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0