Vishal Rao Vishal Rao - 4 months ago 6x
JSON Question

Updating documents in mongodb

I currently have documents in mongodb with the following format:

"title": "name of the document",
"tags" : ["tag1", "tag2", "tag3"]

I want to be able to search for all documents which have "search_term" in their title field and then append "search_term" into their tags field. Is there an easy/clean way to do this without re-ingesting all my documents or do I have to just write a script to do this before inserting them into mongodb all over again?

I did read the mongodb documentation for db.collection.update() which had examples like:

{ name: "Andy" },
name: "Andy",
rating: 1,
score: 1
{ upsert: true }

But this doesn't help me since I don't want to completely replace my "tags" field but rather append to it.

                    {"title" : "search_term"}, 
                    {$push: {"tags": "search_term"}}, 
                    {multi: true}

In general I do migrations/changes over all data sets etc. in a script and run it from an admin route.


  • First JSON: search filter
  • Second JSON: push to the array
  • multi: true if you want to update more than one doc