繁体   English   中英

Mongodb group 然后分别统计实例数

[英]Mongodb group then count number of instances separately

我的收藏中有一些与此类似的数据,

  {name: one, Status: Unauthorised},
  {name: two, Status: Retired},
  {name: three, Status: Authorised},
  {name: two, Status: Unauthorised},
  {name: two, Status: Unauthorised},
  {name: two, Status: Retired},
  {name: three, Status: Unauthorised},
  {name: three, Status: Unauthorised},
  {name: one, Status: Retired},

我如何进行聚合以获取在哪里可以获得未经授权和已停用字段的数量?

我希望输出看起来像这样。

{name: one, Retired: 1, Unauthorised: 1,}
{name: two, Retired: 2, Unauthorised: 2,}
{name: three, Retired: 0, Unauthorised: 2,}

我的代码目前看起来像这样,但是这会为我想要的两个状态带回单独的记录

    {$match: {Status: {$in:["Un-authorised", "Retired"]}}},
    {$group: {_id : {Status:'$Status', machineid:'$name'}, Unauthorised:{$sum :1}}},
    {$sort:{Unauthorised:-1}},
    {$project : {Status: '$_id.Status', machineid:'$_id.name', Unauthorised : '$Unauthorised', _id : 0}},

这是输出等价物

{name: one, Retired: 1,}
{name: one, Unauthorised: 1,}
{name: two, Retired: 2}
{name: two, Unauthorised: 2,}
{name: three, Retired: 0 }
{name: three, , Unauthorised: 2}

你可以试试,

  • $match你的条件
  • $groupnamestatus并获得总状态的总和
  • $group仅按name并推送 k 中的状态和 v 中的值
  • $replaceWith (K,V)阵列到对象使用,以取代根对象,转换状态$arrayToObject使用和合并与名称$mergeObjects
db.collection.aggregate([
  {
    $match: {
      Status: { $in: ["Unauthorised", "Retired"] }
    }
  },
  {
    $group: {
      _id: {
        name: "$name",
        Status: "$Status"
      },
      count: { $sum: 1 }
    }
  },
  {
    $group: {
      _id: "$_id.name",
      status: {
        $push: {
          k: "$_id.Status",
          v: "$count"
        }
      }
    }
  },
  {
    $replaceWith: {
      $mergeObjects: [
        { name: "$_id" },
        { $arrayToObject: "$status" }
      ]
    }
  }
])

操场


第二个选项,用于修复$group状态条件,

  • $group按名称
  • 如果匹配,则使用$cond创建一个字段Retired for sum,然后添加一个否则为零
  • 使用$cond创建一个字段Unauthorised for sum 如果匹配,则添加一个否则为零

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM