[英]How to update one field if the document exist in a collection using mongodb and nodejs?
我是剛接觸mongodb的新手,我不時從一組來源閱讀一組已識別的文檔。 我使用“ _id”字段將文檔保存到集合中,以避免重復。
我想將documentos添加到新文檔中,但是如果存在任何documento,我想更新documento的字段(在這種情況下,增加一個值,例如計數器)。
我想問問mongodb中是否有一種簡單的方法。
通過更新查詢使用upsert
。
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>
}
)
db.students.update(
{ "_id" : "1" },
{ "$set" : { "name" : "Hiren" } },
{ "upsert" : true }
);
如果不存在ID為1的學生,它將添加ID為1並使用名字的新文檔。 如果文檔帶有_id 1,則將其名稱更新為Hiren。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.