How to use Group By and concat fields as string

Viewed 2028

I am novice at MongoDB 3.2,

Consider below example,

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

How can I use Group By _id and create single field with all document fields being concatenated, below is expected output,

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

I used below but it gives array,

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

it gives output as

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

It's working fine i checked

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"]}
                    }
                }
            }
        }
    ]
);
docIwant = db.getCollection('Clients').aggregate(
      [
        {
            $group : {
             _id : "$_id",
             services :  "$services"
            }
        }
      ]
    ).map( doc =>
      Object.assign(
        doc,
       { "services": doc.services.join(",") }
      )
    );
return docIwant[0].
Related