【问题标题】:Group by in mongoDB with property construction在 mongoDB 中通过属性构建进行分组
【发布时间】:2020-07-26 21:42:03
【问题描述】:

我有一个名为 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
    },

    ]

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

我尝试了什么

我试着写在下面的查询

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

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    $group之后使用$push累加器得到分组数据的数组

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

    【讨论】:

    • 上述查询在 RoboMongo 中运行良好,但是当我尝试将其添加到我的节点存储库时,我得到以下类型的异常参数 '{ $match: { account: { $in: any; }; }; }' 不能分配给“any[]”类型的参数。对象字面量只能指定已知属性,而 '$match' 不存在于类型 'any[]' 中。
    • 看起来你正在使用打字稿?请显示您的完整代码
    • 代码在评论中很难发,所以我在stackoverflow.com/questions/61205171/…下面新建了一个问题
    • 我只有一个查询,如果我想将数据属性更改为帐户类型,比如它应该首先出现而不是数据,其次我尝试给它 _id / "$account " 但它不起作用。
    • 使用另一个项目阶段。 { $project: { account: "$_id", data: 1 }}
    猜你喜欢
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    相关资源
    最近更新 更多