Add item to MongoDB document array in PyMongo without reinstalling

I am using MongoDB as the base database for a Python web application (PyMongo + Bottle). Users can upload files and, if necessary, "tag" these files during download. Tags are stored as a list in the document below:

{ "_id" : ObjectId("561c199e038e42b10956e3fc"), "tags" : [ "tag1", "tag2", "tag3" ], "ref" : "4780" } 

I am trying to allow users to add new tags to any document. I came up with something like this:

 def update_tags(ref, new_tag) # fetch desired document by ref key as dict document = dict(coll.find_one({'ref': ref})) # append new tag document['tags'].append(new_tag) # re-insert the document back into mongo coll.update(document) 
Key

(fyi; ref always unique, and it can be easily _id ). There seems to be a way to simply update the value of the tags directly, without tearing the whole document and reinserting it. Did I miss something?

Any thoughts are greatly appreciated :)

+8
python mongodb mongodb-query pymongo
source share
3 answers

You do not need to use to extract the document first just use the .update method using the $push operator.

 def update_tags(ref, new_tag): coll.update({'ref': ref}, {'$push': {'tags': new_tag}}) 

Since the update is deprecated, you should use find_one_and_update or update_one if you are using pymongo 2.9 or later

+12
source share

You can just do

1) If you want to add one entry

 def update_tags(ref, new_tag): coll.update({'ref': ref}, {'$push': {'tags': new_tag}}) 

eg:

 { "_id" : ObjectId("561c199e038e42b10956e3fc"), "tags" : [ "tag1", "tag2", "tag3" ], "ref" : "4780" } >> update_tags("4780", "tag4") {'updatedExisting': True, u'nModified': 1, u'ok': 1, u'n': 1} >> coll.find_one({"ref":"4780"}) { "_id" : ObjectId("561c199e038e42b10956e3fc"), "tags" : [ "tag1", "tag2", "tag3" , "tag4" ], "ref" : "4780" } 

2) If you want to add multiple entries

 def update_tags(ref, new_tag): coll.update({'ref': ref}, {'$pushAll': {'tags': new_tag}}) #type of new_tag is list 

eg:

 { "_id" : ObjectId("561c199e038e42b10956e3fc"), "tags" : [ "tag1", "tag2", "tag3" ], "ref" : "4780" } >> update_tags("4780", ["tag5", "tag6", "tag7"]) {'updatedExisting': True, u'nModified': 1, u'ok': 1, u'n': 1} >> coll.find_one({"ref":"4780"}) { "_id" : ObjectId("561c199e038e42b10956e3fc"), "tags" : [ "tag1", "tag2", "tag3" , "tag4" , "tag5", "tag6", "tag7" ], "ref" : "4780" } 

Note. If the key is not already present, then mongo will create a new key.

+1
source share

Just add the @ssytvane answer and answer @Guarav: you can add "upsert = True" if it does not exist:

 def update_tags(ref, new_tag): coll.update({'ref': ref}, {'$push': {'tags': new_tag}}, upsert = True) 

or

 def update_tags(ref, new_tag): coll.update_one({'ref': ref}, {'$push': {'tags': new_tag}}, upsert = True) 
0
source share

All Articles