Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo+update throw $pull

I have a mongo document:

{ "_id" : 0, "name" : "Vasya", "fav" : [ { "type" : "t1", "weight" : 1.4163 }, { "type" : "t2", "weight" : 11.7772 }, { "type" : "t2", "weight" : 6.4615 }, { "type" : "homework", "score" : 35.8742 } ] }

For delete lowest element in array "fav", I use the following Python code:

db.people.update({"fav":{"type":"t2", "weight":lowest}}, {"$pull":{"fav"{"type":"t2", "weight":lowest}}})

where variable lowest is the lowest value between 6.4615 and 35.8742.

The problem is that this code does nothing. There are no errors, and the values are not deleted from the array. But if I write in the mongo shell the same code, the result is positive.

Unfortunately my experience in pymongo and in mongo is not so good. So if someone knows what the problem is, that would be great.

like image 610
Piston Awesome Avatar asked Dec 11 '25 07:12

Piston Awesome


1 Answers

The syntax works fine for me in Mongo shell and with pymongo, so as suspected the issue is the precision of floating point numbers.

I don't know how you are deriving/computing lowest but you may want to consider standardizing on maximum number of significant digits after the decimal point, or maybe even have a function that normalizes your floats to the same precision, both when you are originally saving documents and when you are later querying or updating them.

Neither Mongo nor Python consider 6.676176060654615 to be equal to 6.67617606065 which explains why your update is having no effect.

like image 174
Asya Kamsky Avatar answered Dec 12 '25 19:12

Asya Kamsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!