[英]Searching for a user by email address in two collections in database MONGODB at the same time
[英]How to save one document into two different collections of same database in mongodb
我正在研究nestjs,我想从collection_1 中获取一个文档并将同一个文档保存到collection_2 中。 我使用了 $out 聚合,但我只能同时在集合 2 中保存一个文档,但是当我尝试保存第二个文档时,第一个文档已经消失了。 我想保存从集合 1 中检索到的集合 2 中的每个文档
服务代码:
async order(name){
const list=await this.usersmodel.find({name:name}).exec()
//return list
try{
if(list){
const x=await this.usersmodel.aggregate([
{ $match: { name: name } },
{$out:"payment"}
])
return "data saved in payment collection"
}
}
catch(error){
return(error.message)
}
}
Controller 代码:
@Post('orderdata')
async orderdata(@Body('name')name){
return this.usersService.order(name)
}
如果您使用的是 Mongo -v 4.2+,则可以使用$merge
await this.usersmodel.aggregate([
{
$match: {
name: name
}
},
{
$merge: "payment"
}
])
$merge
还具有更多选项,可让您在需要时更新现有文档。
不幸的是,如果您使用的是较旧的 Mongo 版本,这无法在 1 次操作中完成,您必须先查询 collection1,然后插入到 collection2 seperatley。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.