简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM