在mongoDB中按属性分组 [英] Group by in mongoDB with property construction

查看:71
本文介绍了在mongoDB中按属性分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Accounts的集合,例如以下数据

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
    },

    ]

希望与帐户分组,并且相应的帐户行应具有该ID的其他相关数据.

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

我尝试过的事情

我尝试在查询下面写

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.

谢谢

推荐答案

$group之后,使用$push累加器获取分组数据的数组

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" },
    },
  }
]);

这篇关于在mongoDB中按属性分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆