Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I push elements to an existing array in MongoDB?

I generate trigram snippets as primary keys. The field words is an array of terms represented by the trigram key, e.g.:

{
    "trigram": "#ha",
    "words": ["hahaha", "harley", "mahalo"]
}

The problem is pushing new terms to the array. I don't know how to use $addToSet for this.

db["Terms"].update({
  "trigram": trigram,
  {"$addToSet": {"words":word}
})

It should append word to the words field. But the database remains empty without returning any error messages.

What should I do?

like image 963
lennyklb Avatar asked Mar 24 '26 12:03

lennyklb


1 Answers

Unless you use the upsert option, an update will only modify existing docs, not create them. Try this instead:

db["Terms"].update(
  { "trigram":trigram }, 
  { "$addToSet":{"words":word} }, 
  upsert=True)

By using the upsert option, it will create the doc if missing, otherwise just update the existing one.

like image 158
JohnnyHK Avatar answered Mar 26 '26 00:03

JohnnyHK