The JOKER
The JOKER

Reputation: 473

Group by in mongoDB with property construction

I have a collection named Accounts like below data

/* 1 */
{
    "_id" : ObjectId("5e93fea52f804ab99b54e4a2"),
    "account" : "first",
    "connect" : "Always",
    "desc" : "first account feature first phase",
    "status" : true
}

/* 2 */
{
    "_id" : ObjectId("5e93fea32c804ab99b12e4d1"),
    "account" : "second",
    "connect" : "Sometimes",
    "desc" : "second account feature first phase",
    "status" : true
}

/* 3 */
{
    "_id" : ObjectId("5e93fea52f804ab99b55a7b1"),
    "account" : "first",
    "connect" : "Sometimes",
    "desc" : "first account feature second phase",
    "status" : true
}

Trying to group and construct data in such a way that query should return a result like below structure

/* First Row */
    "account" : "first",
    [
    {
        _id:ObjectId("5e93fea52f804ab99b54e4a2") 
        "connect" : "Always",
        "desc" : "first account feature first phase",
        "status" : true
    },
    {
        _id:ObjectId("5e93fea52f804ab99b55a7b1") 
        "connect" : "Sometimes",
        "desc" : "first account feature second phase",
        "status" : true
    },

    ]

/* Second Row */
     "account" : "second",
    [
    {
        _id:ObjectId("5e93fea32c804ab99b12e4d1") 
        "connect" : "Always",
        "desc" : "second account feature first phase",
        "status" : true
    },

    ]

Looking to group with Account and the respective account Row should have other related data of that Id.

What i tried

I tried writing below query

db.accounts.aggregate(
    { 
        $match : {account : {$in: ["first", "second"]}}
    }
    ,
    { 
        $group : { 
             _id : "$account"
        }
    }
);

But this is working partially right returning list of accounts like first, second but not related properties.

Thanks

Upvotes: 2

Views: 338

Answers (1)

Ashh
Ashh

Reputation: 46461

After $group use the $push accumulator to get the array of grouped data

db.accounts.aggregate([
  {
    $match: { account: { $in: ["first", "second"] } },
  },
  {
    $group: {
      _id: "$account",
      data: { $push: "$$ROOT" },
    },
  }
]);

Upvotes: 2

Related Questions