【问题标题】:Using a $lookup with $group in Mongo/Mongoose Aggtregation在 Mongodb/Mongoose 聚合中使用 $lookup 和 $group
【发布时间】:2019-01-21 07:25:33
【问题描述】:

我们设置了一些包装请求函数来规范我们处理请求的方式。我们设置的函数之一是聚合函数。它看起来像这样:

  async aggregate(mongooseModelObject, aggregateObject = {}) {
    try {
      return await mongooseModelObject.aggregate(aggregateObject).exec();
    } catch (err) {
      this.sendError(err);
    }
  }

当我这样使用它时效果很好:

exports.getCountByBranch = async function (req, res) {
  let docs;
  let request = new EndpointRequestController(req, res);

  try {
    docs = await request.aggregate(staffmember, [{
      $group: {
        _id: "$branch",
        count: {
          $sum: 1
        }
      }
    }]);
  } catch (err) {
    return request.sendError("An error occurred while trying to find existing records.", err);
  }
  request.documentCount = docs.length;
  request.sendResponse(docs);
}

但是,为了让最终用户对用户更加友好,我想做的是运行 populate 以包含分支“名称”,而不仅仅是“_id”。所以我认为这就像使用$lookup 添加另一个阶段一样简单。如果我只是直接调用 mongoose 函数,我会这样做。也就是说,我试过这个:

exports.getCountByBranch = async function (req, res) {
  let docs;
  let request = new EndpointRequestController(req, res);

  try {
    docs = await request.aggregate(staffmember, [{
      $lookup: {
        from: "branches",
        localField: "branch",
        foreignField: "_id",
        as: "branch"
      },
      $group: {
        _id: "$branch",
        count: {
          $sum: 1
        }
      }
    }]);
  } catch (err) {
    return request.sendError("An error occurred while trying to find existing records.", err);
  }
  request.documentCount = docs.length;
  request.sendResponse(docs);
}

但这会出错:

错误:参数必须是聚合管道运算符

我在这里错过了什么?

【问题讨论】:

  • 试试.allowDiskUse(true)
  • 使用这个 [{ $lookup: { from: "branches", localField: "branch", foreignField: "_id", as: "branch" }}, {$group: { _id: " $branch", count: { $sum: 1 } } }] 花括号在管道阶段没有正确闭合
  • 就是这样,谢谢@SenthurDeva。

标签: node.js mongodb mongoose aggregation-framework


【解决方案1】:

试试这个效果很好

exports.getCountByBranch = async function (req, res) {
let docs;
let request = new EndpointRequestController(req, res);

try {
    docs = await request.aggregate(staffmember, [{
        $lookup: {
            from: "branches",
            localField: "branch",
            foreignField: "_id",
            as: "branch"
        }
    },
    {
        $group: {
            _id: "$branch",
            count: {
                $sum: 1
            }
        }
    }]);
} catch (err) {
    return request.sendError("An error occurred while trying to find existing records.", err);
}
request.documentCount = docs.length;
request.sendResponse(docs);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 2019-09-03
    • 2020-10-05
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多