Concatenate string values in array in a single field in MongoDB

前端 未结 3 1312
醉酒成梦
醉酒成梦 2020-12-08 23:20

Suppose that I have a series of documents with the following format:

{
    \"_id\": \"3_0\",
    \"values\": [\"1\", \"2\"]
}

and I would l

3条回答
  •  无人及你
    2020-12-08 23:50

    You can use the reduce operator together with the substr operator.

    db.collection.aggregate([
    {
        $project: {
            values: {
                $reduce: {
                  input: '$values',
                  initialValue: '',
                  in: {
                    $concat: ['$$value', '_', '$$this']
                  }
                }
            }   
        }       
    },
    {
        $project: {
            values: { $substr: ['$values', 1 , -1]}
        }       
    }])
    

提交回复
热议问题