dlopezgonzalez
dlopezgonzalez

Reputation: 4297

How to update one field if the document exist in a collection using mongodb and nodejs?

I am new dealing with mongodb, I read a set of identified documents from one source time to time. I save the documents to a collection using "_id" field to avoid repetition.

I want to add the documentos to the new documents, but if any documento exist, I want to update a field of the documento (in this case, increase a value like a counter).

I would to ask if there are a easy way to do this in mongodb.

Upvotes: 0

Views: 3926

Answers (1)

Hiren S.
Hiren S.

Reputation: 2832

Make of use upsert with update query.

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>
   }
)



db.students.update(
    { "_id" : "1" }, 
    { "$set" : { "name" : "Hiren" } }, 
    { "upsert" : true } 
);

if student with id 1 doesnot exists it will add new document with id 1 and name hiren. and if document exists with _id 1, then updates its name to Hiren.

Upvotes: 1

Related Questions