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

后端 未结 6 1302
灰色年华
灰色年华 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:14

    Old topic but i had the same problem. Since mongo 2.4, you can use $concat from aggregation framework.

    Example

    Consider these documents :

    {
        "_id" : ObjectId("5941003d5e785b5c0b2ac78d"),
        "title" : "cov"
    }
    
    {
        "_id" : ObjectId("594109b45e785b5c0b2ac97d"),
        "title" : "fefe"
    }
    

    Append fefe to title field :

    db.getCollection('test_append_string').aggregate(
        [
            { $project: { title: { $concat: [ "$title", "fefe"] } } }
        ]
    )
    

    The result of aggregation will be :

    {
        "_id" : ObjectId("5941003d5e785b5c0b2ac78d"),
        "title" : "covfefe"
    }
    
    {
        "_id" : ObjectId("594109b45e785b5c0b2ac97d"),
        "title" : "fefefefe"
    }
    

    You can then save the results with a bulk, see this answer for that.

提交回复
热议问题