MongoDB Aggregation join array of strings to single string

前端 未结 4 871
长发绾君心
长发绾君心 2021-02-12 15:14

We\'re trying to \'join\' an array of strings to a single string within an aggregation.

Given is the following dataset:

Collection 1:

{
  id: 123         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-12 15:17

    Starting Mongo 4.4, the $group stage has a new aggregation operator $accumulator allowing custom accumulations of documents as they get grouped:

    // { "collectionId" : 1234, "name" : "Max"  }
    // { "collectionId" : 876,  "name" : "Rob"  }
    // { "collectionId" : 1234, "name" : "Andy" }
    db.collection.aggregate([
      { $group: {
        _id: "$collectionId",
        names: {
          $accumulator: {
            accumulateArgs: ["$name"],
            init: function() { return [] },
            accumulate: function(names, name) { return names.concat(name) },
            merge: function(names1, names2) { return names1.concat(names2) },
            finalize: function(names) { return names.join(",") },
            lang: "js"
          }
        }
      }}
    ])
    // { "_id" : 876,  "names" : "Rob"      }
    // { "_id" : 1234, "names" : "Max,Andy" }
    

    The accumulator:

    • accumulates on the field name (accumulateArgs)
    • is initialised to an empty array (init)
    • accumulates by concatenating new names to already seen names (accumulate and merge)
    • and finally joins all names as a string (finalize)

提交回复
热议问题