如何将Group By和concat字段用作字符串

时间:2017-11-27 14:57:29

标签: mongodb mongodb-query

我是 MongoDB 3.2 的新手,

考虑下面的例子,

{ "_id" : "2tLX8ALYfRvbgiurZ", "service" : "GSTR 1" }
{ "_id" : "2tLX8ALYfRvbgiurZ", "service" : "GSTR 2" }
{ "_id" : "2tLX8ALYfRvbgiurZ", "service" : "GSTR 3" }

如何使用分组依据 _id创建包含所有文档字段的单个字段,下面是预期输出,

{ "_id" : "2tLX8ALYfRvbgiurZ", "service" : "GSTR 1, GSTR 2, GSTR 3" }

我在下面使用但是它给出了数组,

db.getCollection('Clients').aggregate(
      [
        {
            $group : {
             _id : "$_id",
             services :  "$services"
            }
        }
      ]
    ).map( doc =>
      Object.assign(
        doc,
       { "services": doc.services.join(",") }
      )
    );

它输出为

[{ "_id" : "2tLX8ALYfRvbgiurZ", "service" : "GSTR 1, GSTR 2, GSTR 3" }]

1 个答案:

答案 0 :(得分:1)

我检查正常

db.client.insert([
    { "id" : "2tLX8ALYfRvbgiurZ", "service" : "GSTR 1" },
    { "id" : "2tLX8ALYfRvbgiurZ", "service" : "GSTR 2" },
    { "id" : "2tLX8ALYfRvbgiurZ", "service" : "GSTR 3" }
]);



db.getCollection('client').aggregate([{$group:{_id:"$id",myfield:{$push:{$concat:["$service"]}}}},{$project:{"results":{$reduce:{input:"$myfield",initialValue:'',in:{$concat:["$$value",", ","$$this"]}}}}}]);