mongodb - mongoDB 中的 Group by 与属性构造

标签 mongodb mongoose group-by mongodb-query aggregation-framework

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

/* 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
}

尝试以查询应返回如下结构的结果的方式对数据进行分组和构造

/* 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 的其他相关数据。

我尝试过的

我尝试编写以下查询

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

但这部分工作正常,返回帐户列表,例如第一个、第二个但不相关的属性。

谢谢

最佳答案

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

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

关于mongodb - mongoDB 中的 Group by 与属性构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61203003/

相关文章:

mysql - 如何使用sql查询将同一字段分组在一个字段下

database - 在 MongoDB atlas 中构建开发和生产环境

python - 如何在 Python 中加入 MongoDB 集合?

javascript - 我的作业项目 : Stock Price Checker 的异步/等待问题

javascript - Mongo - 多个引用对象数组中的值的总和

node.js - 创建添加到数组字段的新子项

sql - 每行SQL中相同ID的总和

sql - 条件分组子句(sqlite)

node.js - 如何使用 set NODE_ENV=product && nodemon 连接在线数据库?

mongodb - 我可以使用对象的属性在 mongo 更新中进行基本数学运算吗?