Kvlknctk
Kvlknctk

Reputation: 670

Transform field in MongoDB aggregate

I have a some query on mongodb via aggregate, I can get the result I want and sent to client. After this I need to be merge file name and file url.

My results

{
  "_id" : "1", "name" : "x", "image" : "y.jpg"
}

But I want to edit results like this

{
  "_id" : "1", "name" : "x", "image" : "http:/x.com/y.jpg"
}

I can edit the results after aggregate in a loop. but can aggregate give this to me as I want?

Upvotes: 1

Views: 1305

Answers (1)

Demo - https://mongoplayground.net/p/nWv7d2Ld5sy

Use $set and $concat

   db.collection.aggregate([
      {
        $set: {
          image: {
            $concat: [ "http://", "$name", ".com/", "$image" ] // combine to form the output
          }
        }
      }
    ])

Upvotes: 3

Related Questions