Append a string to the end of an existing field in MongoDB

Starting Mongo 4.2, db.collection.updateMany() can accept an aggregation pipeline, finally allowing the update of a field based on its current value:

// { a: "Hello" }
db.collection.updateMany(
  {},
  [{ $set: { a: { $concat: [ "$a", "World" ] } } }]
)
// { a: "HelloWorld" }
  • The first part {} is the match query, filtering which documents to update (in this case all documents).

  • The second part [{ $set: { a: { $concat: [ "$a", "World" ] } } }] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set (alias of $addFields) is a new aggregation operator which in this case replaces the field’s value (by concatenating a itself with the suffix "World"). Note how a is modified directly based on its own value ($a).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)