Update data in array in mongoDB

Hello Everyone,

I am a bit new to node and mongoDB what I want it when user enters new data it should get stored in database, but whne user tries to enter a new record but if record name already exists it should update the previous record in which older data should bot be delete but should be updates in an array,

for eg.: if name: Juned
after updateing it should be name {

how can I do this and what will be the query for this

Thanks in advance
Juned Adenwalla,

Hi @Juned_Adenwalla ,

I beilive you need to use $push array operator:

db.collection.updateOne({ _id : <SOME ID>}, {$push : { name : "john" }});

Since name is initialy an array it should add it to the end of an array.

_id : <SOME ID>,
name : [ "juned", "john"]


Thank you for your valuable time and reply but when I try the code above I get the following error

MongoError: The field ‘project’ must be an array but is of type string in document

The code I am using is shared below :

var r = await model.updateMany({ resource: req.params.name}, {$push : {remark: req.body.remark, project: req.body.project, reporting_to : req.body.reporting_to}});

@Juned_Adenwalla ,

Of course name field must be an array. I thought that initially the document has :

name : [ "juned"]

Make sure that the first name when you insert a document gets as a single element array. Or any other field that needs to use a push mechanisms…