Skip to content

Instantly share code, notes, and snippets.

@szy0syz
Last active March 11, 2021 03:25
Show Gist options
  • Save szy0syz/c07db542ec3406d2dc987eeb1ad9f3e9 to your computer and use it in GitHub Desktop.
Save szy0syz/c07db542ec3406d2dc987eeb1ad9f3e9 to your computer and use it in GitHub Desktop.
MongoDB

容器

backup

docker exec mymongo sh -c 'exec mongodump -d elev -o /data/db/elev_bak_20210220_1'

docker exec mymongo sh -c 'exec mongorestore -d elev ./data/db/elev_bak_20210220_1/elev --drop'

tar -zcvf elev_bak_20210220_1.tar.gz ./elev_bak_20210220_1
tar -zxvf elev_bak_20210220_1.tar.gz

查询

aggregate

  • 先过滤状态和创建时间
    • 先过滤单据的完成状态和创建时间
  • 然后先按电梯再按项目分组
    • 用电梯和项目同时分组
    • 这个时候过滤到的数据就是:这个时间段里的这个项目里的电梯个体重复出现的次数
    • 这个其实可以合并了做,毕竟一个电梯只可能出现在一个项目,但更严谨点吧
  • 在匹配过滤
    • 匹配出重复了3次的个体
  • 再分组
    • 用项目id合并数据
  • 关联
    • 外联集合翻译下项目名
  • 投影
    • 去除多余的字段(应该可以再关联时就投影)
  • 展开
    • 展开数组
  • 排序
db.repairIssues.aggregate([
  {
    $match: {
      status: 10,
      createdAt: {
        $gte: ISODate('2020-12-01T00:00:00.000Z'),
        $lte: ISODate('2020-12-31T23:59:59.000Z')
      }
    }
  },
  {
    $group: {
      _id: {
        elevator: '$elevator',
        orgUnit: '$adminOrgUnit'
      },
      count: { $sum: 1 }
    }
  },
  {
    "$match": {
      count: { $gt: 3 }
    }
  },
  {
    $group: {
      _id: '$_id.orgUnit',
      count: { $sum: 1 }
    }
  },
  {
    $lookup: {
      from: 'baseUnits',
      localField: '_id',
      foreignField: '_id',
      as: 'adminOrg'
    }
  },
  {
    $project: {
      'adminOrg.title': 1,
      'count': 1
    }
  },
  {
    $unwind: '$adminOrg'
  },
  {
    $sort: {
      count: -1
    }
  }
]);
  • 以上是 lookup 阶段没合并投影
  • 以下是 lookup 阶段一起做投影
db.repairIssues.aggregate([
  {
    $match: {
      status: 10,
      createdAt: {
        $gte: ISODate('2020-10-04T07:23:06.952Z'),
        $lte: ISODate('2021-01-31T07:23:06.952Z')
      }
    }
  },
  {
    $group: {
      _id: {
        elevator: '$elevator',
        orgUnit: '$adminOrgUnit'
      },
      count: { $sum: 1 }
    }
  },
  {
    $match: {
      count: { $gt: 3 }
    }
  },
  {
    $group: {
      _id: '$_id.orgUnit',
      count: { $sum: 1 }
    }
  },
  {
    $lookup: {
      from: 'baseUnits',
      let: { orgUnit: '$_id' },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [{ $eq: ['$_id', '$$orgUnit'] }]
            }
          }
        },
        {
          $project: {
            'adminOrg.title': 1,
            count: 1
          }
        }
      ],
      as: 'adminOrg'
    }
  },
  {
    $unwind: '$adminOrg'
  },
  {
    $sort: {
      count: -1
    }
  }
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment