How to use $push overwrites existing value rather than adds to the end of an array within a document

Hi, I have a document like this

{ "_id" : 23, "local_id" : 1234, "global_id" : [ "P123", "P345" ] }

If I want to $push new value to the array has the key “global_id” then I can do this

collection.update_one({‘local_id’: l_pid}, {’$push’: {‘global_id’: global_id}})

and the document looks sth like this , for example : (push P678 to the array)

{ “_id” : 23, “local_id” : 1234, “global_id” : [ “P123”, “P345”, “P678” ] }

But next time when the same key of “global_id” comes in it keeps appending to the end of array like : (this time the same P678 comes in)

{ “_id” : 23, “local_id” : 1234, “global_id” : [ “P123”, “P345”, “P678” , “P678”] }

I want it to overwrite to existing value, and the array has to have unique value, the value can’t be the same.

How can I do it?

HELPP. Is anyone knows

use $addToSet rather than $push


Thanks, thats what I want

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.