【问题标题】:How to transfer multiple data from one collection to another using $out aggregation如何使用 $out 聚合将多个数据从一个集合传输到另一个集合
【发布时间】:2020-05-11 07:37:57
【问题描述】:

我正在研究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】:

    根据文档,$out 正在用您提供的集合替换整个集合(如果存在),所以当您这样做时,它将替换旧集合

    如果您的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)
        }
    }
    

    希望对你有帮助

    【讨论】:

    • 现在一切正常,我又遇到了一个问题,我想存储多个文档,例如假设我已经从 collection_1 将 doc_1、doc_2、doc_3、doc_4 保存在 collection_2 中,情况出现了我再次需要将相同的 doc_1 保存在从 collection_1 中获取的 collection_2 中。我的收藏中没有相同文档的重复条目。如何做到这一点。你能提供任何解决方案吗?
    • 如果您需要覆盖现有的doc_1,则使用{ $merge: { into: "payment", on: "_id", whenMatched: "replace" } } .... 如果您需要保留当前的,请使用{ $merge: { into: "payment", on: "_id", whenMatched: "keepExisting" } } ... 如果您需要合并新的与现有的使用{ $merge: { into: "payment", on: "_id", whenMatched: "merge" } } ...阅读文档以获取更多信息docs.mongodb.com/manual/reference/operator/aggregation/merge/…
    • 不,我不想将新的合并到现有的中。如果该文档已经存在,我需要一次又一次地添加相同的文档。假设我已经将 doc_1 保存在 collection_2 中,然后我将 doc_2 保存在 collection_2 中,现在我需要在 collection_2 中再添加一个文档 doc_1。我使用了您之前评论的第三个查询,但输出仍然保持不变。
    • 为了更清楚,你可以检查这个-stackoverflow.com/questions/61768900/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2020-01-09
    • 2023-03-31
    • 2013-06-17
    • 2015-09-14
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多