[英]How to save one document into two different collections of same database in mongodb
I am working on nestjs and I want to fetch one document from collection_1 and save that same document into collection_2.我正在研究nestjs,我想从collection_1 中获取一个文档并将同一个文档保存到collection_2 中。 I used $out aggregation but I only able to save one document in collection 2 at the same time but when I trying to save the second document then the first document has vanished.我使用了 $out 聚合,但我只能同时在集合 2 中保存一个文档,但是当我尝试保存第二个文档时,第一个文档已经消失了。 I want to save every document in collection 2 which is retrieved from the collection 1我想保存从集合 1 中检索到的集合 2 中的每个文档
Service code:服务代码:
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 code: Controller 代码:
@Post('orderdata')
async orderdata(@Body('name')name){
return this.usersService.order(name)
}
If you're on Mongo -v 4.2+ you can use $merge如果您使用的是 Mongo -v 4.2+,则可以使用$merge
await this.usersmodel.aggregate([
{
$match: {
name: name
}
},
{
$merge: "payment"
}
])
$merge
also has more option to allow you to update existing documents if needed. $merge
还具有更多选项,可让您在需要时更新现有文档。
Unfortunately if you're on on older Mongo version this cannot be done in 1 action, you'll have to first query collection1 and then insert to collection2 seperatley.不幸的是,如果您使用的是较旧的 Mongo 版本,这无法在 1 次操作中完成,您必须先查询 collection1,然后插入到 collection2 seperatley。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.