Open
Description
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
Labels
No labels