如何使用$ out聚合将多个数据从一个集合传输到另一个集合 [英] How to transfer multiple data from one collection to another using $out aggregation

查看:201
本文介绍了如何使用$ out聚合将多个数据从一个集合传输到另一个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on nestjs and I have two collections one is order and the second is payment. Now I need to retrieve one document from the collection order and save it into payment collection which is working properly but the issue is when I am trying to save the second document into payment collection then my first document is overwritten. In other words, the first document has vanished after submitting the second document. I want to save every document in payment collection which i retrieved from orders document.

以下是服务代码:

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

推荐答案

根据文档,$out会将整个集合(如果存在)替换为您提供的集合,因此当您执行操作时,它将替换旧的

according to the docs, $out is replacing the whole collection if it exists, with the one you provided, so when you do it, it will replace the old one

如果您的mongodb版本> 4.2,则可以使用$merge代替,

if your mongodb version is > 4.2, you can use $merge instead,

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

in $merge, it adds the new document to the collection if it exists, also you can define the behavior if the new document already exists (keep the old one, or overwrite it) and if it does not exist (insert or ignore it)

您可以在 $ merge here

您还可以找到 $之间的比较并在此处合并$ a

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

in your code, it should be something like

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

希望有帮助

这篇关于如何使用$ out聚合将多个数据从一个集合传输到另一个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆