如何使用$ out聚合将多个数据从一个集合传输到另一个集合

问题描述 投票:0回答:1

我正在使用nestjs,我有两个集合,一个是订单,第二个是付款。现在,我需要从催款单中检索一个文档,并将其保存到可以正常工作的付款收款系统中,但是问题是当我尝试将第二个文档保存到付款收款时,我的第一个文档被覆盖了。换句话说,第一份文件在提交第二份文件后消失了。我想将每个文件保存在从订单文件中检索到的付款集合中。

这里是服务代码:

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)
    }
}

控制器代码::

@Post('orderdata')
async orderdata(@Body('name')name){
    return this.usersService.order(name)
}
typescript postman aggregate lookup nestjs
1个回答
0
投票
如果您的mongodb版本为> 4.2,则可以改用$merge

$merge中,它将新文档添加到集合中(如果存在),还可以定义行为,如果新文档已经存在(保留旧文档或覆盖它)并且不存在(插入或删除)忽略它)

您可以在$merge here的文档中看到所有这些内容>

您也可以找到$out and $merge here之间的比较>

在您的代码中,应该类似于

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 } }, { $merge: { into: "payment" } } // you can define other options here like if the document already exists, keep the old one or not and so on, all of that you can find in the documentation ]) return "data saved in payment collection" } } catch(error){ return(error.message) } }

希望有帮助

© www.soinside.com 2019 - 2024. All rights reserved.