How to transfer multiple data from one collection to another using $out aggregation

不问归期 提交于 2020-05-17 06:43:10

问题


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.

Here is the code of service:

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

code of controller-:

@Post('orderdata')
async orderdata(@Body('name')name){
    return this.usersService.order(name)
}

回答1:


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

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)

you can see all of that in the documentation of $merge here

also you can find a comparison between $out and $merge here

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

hope it helps



来源:https://stackoverflow.com/questions/61700144/how-to-transfer-multiple-data-from-one-collection-to-another-using-out-aggregat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!