Concatenate string values in array in a single field in MongoDB

前端 未结 3 1294
醉酒成梦
醉酒成梦 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:49

    Starting in Mongo 4.4, the $function aggregation operator allows applying a custom javascript function to implement behaviour not supported by the MongoDB Query Language.

    For instance, in order to concatenate an array of strings:

    // { "_id" : "3_0", "values" : [ "1", "2" ] }
    db.collection.aggregate(
      { $set:
        { "values":
          { $function: {
              body: function(values) { return values.join('_'); },
              args: ["$values"],
              lang: "js"
          }}
        }
      }
    )
    // { "_id" : "3_0", "values" : "1_2" }
    

    $function takes 3 parameters:

    • body, which is the function to apply, whose parameter is the array to join.
    • args, which contains the fields from the record that the body function takes as parameter. In our case "$values".
    • lang, which is the language in which the body function is written. Only js is currently available.

提交回复
热议问题