I have written a python program that creates a mongoDB database.
I have written function that is supposed to update this databse.
I've searched through many many forum posts for similar problems, but none of them seem to address this exact one.
Basically, My objects are very simple and like so.
object{
 'foo' : 'bar'
 'baz' : [foobar,foobarbaz,]
}
I basically create these objects, then, if they are repeated I update them with a function like this:
db["collection"].update({u'foo' : bar},{'$push':{u'baz' : foobaz}})
I am trying to append a string to the list which is the value for the field name 'baz'.
However, I keep getting this object in return:
{'updatedExisting': False, u'nModified': 0, u'ok': 1.0, u'n': 0}
I've tried replacing update with update_one.
I am using python 2.7, Ubuntu 16.04, pymongo 2.7.2,
mongodb 3.6.3
Thanks!
Ok I figured this one out.
Because I was getting the proper format returned, that means that I was trying to communicate with db, but something was amiss with the python/javascript communication.
I'm pretty sure that python does not understand javascript.
That is why everything must be explictly stated as a string.
For example, with:
db["collection"].update({u'foo' : bar},{'$push':{u'baz' : foobaz}}).
Notice how I must use 'foo' instead of foo.
The same goes for the values.
I am updating the values by a variable passed into a function.
In order for pymongo to correctly convert this into javascript to communicate with my mongoDB database, i must also explicitly convert it into a string with str(bar) and str(foobaz).
None of this would be possible with python unless I was using pymongo.
So in order for pymongo to do it's magic, I must give it the proper format.
This doesn't seem to apply to all versions of python and pymongo, as i've searched this problem and none of the people using pymongo had to use this specific conversion. This may also have something to do with the fact that i'm using python 2.7. I know that the typechecking/conversion is a little different in python3 in some instances.
If someone can explain this in a more lucid way (using the correct python and javascript terminology) that would be great.
Update: This also seems to hold true for any type.
eg. in order to increment using the $inc operator with 1, I must also use int(1) to convert my int into an int explicitly. (Even though this is kind of weird, because int should be primitive, but maybe it's an object in python).
MongoDB / PyMongo / Python update not working