【问题标题】:Mongodb Group stage, and query last two documentMongodb Group阶段,并查询最后两个文档
【发布时间】:2020-02-13 14:53:26
【问题描述】:

在 mongodb 中,如果我们想获取小组赛的第一个或最后一个文档,那么 FIRST 和 LAST 运算符会有所帮助。我想根据 _id:"$department" 对集合进行分组,并获取 LAST 文档和 LAST-1 文档。有什么办法可以做到这一点。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    假设你有这个收藏:

    [
      { department: "HR", employees: 20 },
      { department: "Finance", employees: 30 },
      { department: "Sales", employees: 5 },
      { department: "IT", employees: 50 }
    ]
    

    然后你可以运行这个聚合:

    db.collection.aggregate([
       { $sort: { department: 1 } },
       {
          $group: {
             _id: null,
             employees: { $sum: "$employees" },
             all_departments: { $push: "$department" }
          }
       },
       {
          $set: {
             last_departments: {
                $concatArrays: [
                   [{ $arrayElemAt: ["$all_departments", -1] }],
                   [{ $arrayElemAt: ["$all_departments", -2] }]
                ]
             }
          }
       }
    ])
    

    蒙古Playground

    更新

    $slice 更短:

    db.collection.aggregate([
       { $sort: { department: 1 } },
       {
          $group: {
             _id: null,
             employees: { $sum: "$employees" },
             all_departments: { $push: "$department" }
          }
       },
       { $set: { last_departments: { $slice: ["$all_departments", -2] } } }
    ]) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      相关资源
      最近更新 更多