Append item to MongoDB document array in PyMongo without re-insertion
NickName:deadbits Ask DateTime:2015-10-18T01:06:10

Append item to MongoDB document array in PyMongo without re-insertion

I am using MongoDB as the back-end database for Python web application (PyMongo + Bottle). Users can upload files and optionally 'tag' these files during upload. The tags are stored as a list within the document, per below:

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

I am trying to allow users to append 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)

(fyi; ref key is always unique. this could easily be _id as well.) It seems like there should be a way to just update the 'tags' value directly without pulling back the entire document and re-inserting. Am I missing something here?

Any thoughts are greatly appreciated :)

Copyright Notice:Content Author:「deadbits」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/33189258/append-item-to-mongodb-document-array-in-pymongo-without-re-insertion

Answers
styvane 2015-10-17T17:18:37

You don't need to use to retrieve the document first just use the .update method with the $push operator.\n\ndef update_tags(ref, new_tag):\n coll.update({'ref': ref}, {'$push': {'tags': new_tag}})\n\n\nSince update is deprecated you should use the find_one_and_update or the update_one method if you are using pymongo 2.9 or newer",


Kiluvya.A 2017-09-15T02:05:23

Just to add to @ssytvane answer,and to answer @Guarav: you can add \"upsert = True\" if it does not exist:\n\ndef update_tags(ref, new_tag):\n coll.update({'ref': ref}, {'$push': {'tags': new_tag}}, upsert = True)\n\n\nor\n\ndef update_tags(ref, new_tag):\n coll.update_one({'ref': ref}, {'$push': {'tags': new_tag}}, upsert = True)\n",


Nikhil Fulzele 2017-10-12T05:47:52

You can simply do\n\n1) If you want to append single entry\n\ndef update_tags(ref, new_tag):\n coll.update({'ref': ref}, {'$push': {'tags': new_tag}})\n\n\neg: \n\n{\n \"_id\" : ObjectId(\"561c199e038e42b10956e3fc\"),\n \"tags\" : [ \"tag1\", \"tag2\", \"tag3\" ],\n \"ref\" : \"4780\"\n}\n>> update_tags(\"4780\", \"tag4\")\n{'updatedExisting': True, u'nModified': 1, u'ok': 1, u'n': 1}\n>> coll.find_one({\"ref\":\"4780\"})\n{\n \"_id\" : ObjectId(\"561c199e038e42b10956e3fc\"),\n \"tags\" : [ \"tag1\", \"tag2\", \"tag3\" , \"tag4\" ],\n \"ref\" : \"4780\"\n}\n\n\n2) If you want to append multiple entries\n\ndef update_tags(ref, new_tag):\n coll.update({'ref': ref}, {'$pushAll': {'tags': new_tag}}) #type of new_tag is list\n\n\neg: \n\n{\n \"_id\" : ObjectId(\"561c199e038e42b10956e3fc\"),\n \"tags\" : [ \"tag1\", \"tag2\", \"tag3\" ],\n \"ref\" : \"4780\"\n}\n>> update_tags(\"4780\", [\"tag5\", \"tag6\", \"tag7\"])\n{'updatedExisting': True, u'nModified': 1, u'ok': 1, u'n': 1}\n>> coll.find_one({\"ref\":\"4780\"})\n{\n \"_id\" : ObjectId(\"561c199e038e42b10956e3fc\"),\n \"tags\" : [ \"tag1\", \"tag2\", \"tag3\" , \"tag4\" , \"tag5\", \"tag6\", \"tag7\" ],\n \"ref\" : \"4780\"\n}\n\n\nNote: If the key is not already present, then mongo will create new key.",


ArminMz 2020-03-30T14:03:14

There had been some good answers that are correct but in my opinion writing update_tags this way is better and more usable:\n\ndef update_tags(ref, *args):\n coll.update_one(ref, {'$push': {'tags': {'$each': args}}})\n\n\nthis way you can do both appending one tag or appending many tags:\n\n>> update_tags(ref, 'tag5')\n\n\n>> update_tags(ref, 'tag5', 'tag6')\n\n\n>> list_of_new_tags = do_something_that_returns_list_of_tags()\n>> update_tags(ref, *list_of_new_tags)\n",


More about “Append item to MongoDB document array in PyMongo without re-insertion” related questions

Append item to MongoDB document array in PyMongo without re-insertion

I am using MongoDB as the back-end database for Python web application (PyMongo + Bottle). Users can upload files and optionally 'tag' these files during upload. The tags are stored as a list withi...

Show Detail

Append new value to a list in PyMongo

I have a collection in MongoDB that I store on mlab like this { 'course_id': '...', 'course_description: '...', 'reviews:' [ { 'hours': ...

Show Detail

Append item to Mongo Array

I have a mongodb document I am trying to update. This answer was helpful, but every time I insert into the database, the data is inserted as an array inside of the array whereas I just want to inse...

Show Detail

Document level locking in mongodb with Pymongo

I am trying to achieve document level locking in MongoDB3.0 with wiredTiger storage Engine. What I want to achieve is -> read a document -> lock it -> perform some operation on the data -> store ...

Show Detail

Insert document in MongoDB using pymongo

I'm using Python for the first time to run a crawler. I've got the crawler to work and now I want to save the results in my MongoDB using pymongo,but for some reason I get this error: "NameError: n...

Show Detail

How to append a new array of values to an existing array document in mongodb using pymongo?

An existing collection like as below: "_id" : "12345", "vals" : { "dynamickey1" : {} } I need to add "vals" : {

Show Detail

Mongodb pymongo errors DocumentTooLarge

I am trying to do the following query: Query the problem is {"id": {"$nin": lista}}. lista is an array of ids that cointains 1.000.000 ids exceeding 98MB size. Since Mongodb has a

Show Detail

How to sort mongodb with pymongo

I'm trying to use the sort feature when querying my mongoDB, but it is failing. The same query works in the MongoDB console but not here. Code is as follows: import pymongo from pymongo import

Show Detail

How to sort mongodb with pymongo

I'm trying to use the sort feature when querying my mongoDB, but it is failing. The same query works in the MongoDB console but not here. Code is as follows: import pymongo from pymongo import

Show Detail

How to sort mongodb with pymongo

I'm trying to use the sort feature when querying my mongoDB, but it is failing. The same query works in the MongoDB console but not here. Code is as follows: import pymongo from pymongo import

Show Detail