【问题标题】:How to get both data results & counts from aggregate in mongodb如何从 mongodb 中的聚合中获取数据结果和计数
【发布时间】:2020-07-18 02:58:23
【问题描述】:

我遇到了一个问题 我在三个集合中使用聚合。所以,我想要聚合结果+单个查询中的结果计数,但由于我也在聚合中使用限制,所以我想要总计数但不仅仅是限制。 这是我的查询

var partnerCollection = [
    { $lookup: {
      from: "courses",
      localField: "_id",
      foreignField: "partnerId",
      as: "courses"
    } },
    {
        $project:
        {
            "_id":1,
            "partnerName":1,
            "phone":1,
            "email":1,
            "website":1,
            "address":1,
            "companyId":1,
            "courses.courseName": 1,
            "courses.courseType":1,
            "courses.totalCost":1,
            "courses.costPerWeek":1
        }
    },
    {
        $match: findUserDataCondition
    },
    {
        $sort: {
            [sortby] : sortType
        }
    },
    {
        $skip : start
    },
    {
        $limit : length
    } ];

partnerBusiness.aggregate(partnerCollection, (error, result) => {
});

我想得到上述查询的结果(包括$limit)+计数(所有匹配的集合,计数我想忽略$limit), 请帮我解决这个问题。

我希望我的结果是这样的

data: [{ _id: 5d02e292a9ce94663c6aafd6,
    partnerName: 'aaaa',
    email: 'aaaa@jcub.edu.au',
    phone: '1300935386',
    website: 'abc.com',
    companyId: 5ce3548c52e4920ae3f3f12f,
    courses: []
  }, { _id: 5d02e292a9ce94663c6aafd6,
    partnerName: 'bbb',
    email: 'bbb@jcub.edu.au',
    phone: '1300935386',
    website: 'abc.com',
    companyId: 5ce3548c52e4920ae3f3f12f,
    courses: []
  },
  { ........ },
],
count : 90

【问题讨论】:

标签: node.js mongodb aggregation-framework


【解决方案1】:

在聚合上使用 toArray 方法,然后你可以找到它的长度

【讨论】:

    猜你喜欢
    • 2021-07-01
    • 2020-06-25
    • 2016-07-13
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2016-02-03
    相关资源
    最近更新 更多