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

后端 未结 6 1286
灰色年华
灰色年华 2020-12-02 23:22

I have a document with a field containing a very long string. I need to concatenate another string to the end of the string already contained in the field.

The way I

6条回答
  •  攒了一身酷
    2020-12-03 00:09

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

    // { a: "Hello" }
    db.collection.update(
      {},
      [{ $set: { a: { $concat: [ "$a", "World" ] } } }],
      { multi: true }
    )
    // { 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).

    • Don't forget { multi: true }, otherwise only the first matching document will be updated.

提交回复
热议问题