Conditionally add to the end of a string

Hi, I’m working on a project where I need to conditionally add an ! to the end of the users name if its _id matches the one given. I think I should be able to do this using $concat, but I’ve tried playing around with this in mongo playground, but I can’t seem to get it to work. I would really appreciate any help or advice. Thank you!

https://mongoplayground.net/p/WitBRRL3Nlc

Note: My document looks like this:

[
 _id: '63410263611986740717e152'
users: [{
_id: '62211243611986740717e152'
name: John
},
{
_id: '61111243611986740717e152'
name: Jane
},
]
]

And I need to add ! to the end of the name if the users id is equal to the one given

Hello @Geenzie,

Based off the playground link, I assume the provided value in this case is 12 in which you want the name "John" to turn into "John!" - However, please correct me if I am wrong here.

Would the following work for you? I only tested it on the playground sample documents:

db.collection.update({
  _id: 1
},
[
  {
    $set: {
      "users": {
        $map: {
          input: "$users",
          as: "users",
          in: {
            $cond: {
              if: {
                $eq: [
                  "$$users._id",
                  12
                ]
              },
              then: {
                "_id": "$$users._id",
                "name": {
                  $concat: [
                    "$$users.name",
                    "!"
                  ]
                }
              },
              else: {
                "_id": "$$users._id",
                "name": "$$users.name"
              }
            }
          }
        }
      }
    }
  }
])

Ref: Playground link

When the name did not match the provided value, I set the _id and name values to what they already were / are.

Please test thoroughly to ensure this suits all your use case and requirements as I have only tried this on the playground sample documents.

For reference, I utilised $map in this example.

Hope the above helps.

Regards,
Jason

Hi @Jason_Tran,

Thank you for your response! This worked. I have a question though. Is there a way to conditionally $set/ change where only the user whose _id matches data would be updated? I’m pretty new to this, but it seems like this could be an expensive process. Would a simple $push and $pull be less energy/ performance intensive?