簡體   English   中英

獲取文檔(如果存在)並插入並返回 ZCCADCDEDB567ABAE643E15DCF0974E503Z 中的插入文檔

[英]Get documents if they exist and insert them and return the insert document in Mongoose

我的 MongoDB 數據庫["student1", "student2", "student3"]中有一個學生列表如下,我正在嘗試運行一個查詢,其中我有另一個列表["student5", "student2", "student7"] 鑒於我已經有"student2" ,我不想更新它。 我只想插入student5", and "student7" 。插入后,我想返回所有學生的文檔["student5", "student2", "student7"] 。使用 Mongoose 可以這樣做嗎?

是的,您需要將$addToSet運算符與$each修飾符一起使用。

db.collection.updateOne(
   { _id: 1 },
   { $addToSet: { students: { $each: [ "student2", "student5", "student7" ] } } },
   { new: true }
 )

參考文檔鏈接: https://www.mongodb.com/docs/manual/reference/operator/update/addToSet/#-each-modifier

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM