You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
importmongomockclassMongoClientMock(mongomock.MongoClient):
def__init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
defstart_session(self, *args, **kwargs):
returnsuper().start_session(*args, **kwargs)
defwithout_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 queryfound_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 queryupdated_response=mock_mongo.db.my_collection.find_one(
{"field1": "mynewdata"}
)
print(updated_response)
# These documents should be the same but are differentdefwith_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 includedif__name__=="__main__":
without_id()
with_id()
The text was updated successfully, but these errors were encountered:
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:
The text was updated successfully, but these errors were encountered: