简体   繁体   中英

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. 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. I want to save every document in collection 2 which is retrieved from the collection 1

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:

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

If you're on Mongo -v 4.2+ you can use $merge

await this.usersmodel.aggregate([
    {
        $match: {
            name: name
        }
    },
    {
        $merge: "payment"
    }
])

$merge also has more option to allow you to update existing documents if needed.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM