[英]Get documents if they exist and insert them and return the insert document in Mongoose
I have a list of students as the following in my MongoDB database ["student1", "student2", "student3"]
and I am trying to run a query where I have another list ["student5", "student2", "student7"]
.我的 MongoDB 数据库["student1", "student2", "student3"]
中有一个学生列表如下,我正在尝试运行一个查询,其中我有另一个列表["student5", "student2", "student7"]
。 Given that I already have "student2"
I do not want to update it.鉴于我已经有"student2"
,我不想更新它。 I just want to insert student5", and "student7"
. After insertion, I want to return the document of all the students ["student5", "student2", "student7"]
. Is it possible to do so using Mongoose?我只想插入student5", and "student7"
。插入后,我想返回所有学生的文档["student5", "student2", "student7"]
。使用 Mongoose 可以这样做吗?
Yes, you need to use $addToSet
operator with $each
modifier.是的,您需要将$addToSet
运算符与$each
修饰符一起使用。
db.collection.updateOne(
{ _id: 1 },
{ $addToSet: { students: { $each: [ "student2", "student5", "student7" ] } } },
{ new: true }
)
Documentation link for reference: https://www.mongodb.com/docs/manual/reference/operator/update/addToSet/#-each-modifier参考文档链接: https://www.mongodb.com/docs/manual/reference/operator/update/addToSet/#-each-modifier
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.