How to save one document into two different collections of same database in mongodb

Viewed 152

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

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.

Related