Sree
Sree

Reputation: 971

How to update/insert into a mongodb collection with the result of aggregate query on the another collection

I have a below aggregate query and I wanted to insert/update this result into another collection.

db.coll1.aggregate([
    {
        $group: 
        {
            _id: "$collId",
            name: {$first:"$name"} ,
            type: {$first:"$Type"}  ,
            startDate: {$first:"$startDate"} ,
            endDate: {$first:"$endDate"} 
        }
    }
    ])

I have another collection coll2, which has fields in the above query and some additional fields too. I may already have the document created in Coll2 matching the _id:collId in the above query. If this Id matches, I want to update the document with the field values of the result and keep the values of other fields in the document. If the Id does not exists, it should just create a new document in Coll2.

Is there a way to do it in the MongoDB query. I want to implement this in my Spring application.

Upvotes: 1

Views: 1672

Answers (1)

Himanshu Sharma
Himanshu Sharma

Reputation: 3010

We can use $merge to do that. It's supported from Mongo v4.2

db.collection.aggregate([
    {
        $group:{
            "_id":"$collId",
            "name": {
                $first:"$name"
            },
            "type":{
                $first:"$Type"
            },
            "startDate":{
                $first:"$startDate"
            },
            "endDate":{
                $first:"$endDate"
            } 
        }
    },
    {
        $merge:{
            "into":"collection2",
            "on":"_id",
            "whenMatched":"replace",
            "whenNotMatched":"insert"
        }
    }
])

Upvotes: 2

Related Questions