繁体   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