1

I am looking to find out the total documents count from aggregate join. is it possible to get count from the below code? if anybody have an idea please let me know.

    db.collection("camp", function (err, camp) {
    camp.aggregate([{$match: {status: {$ne: "Rejected"}}}, 
         {'$lookup': {

                from: "organization",
                localField: "organization",
                foreignField: "organizationId",
                as: "orgnData"
            }
        }, {'$lookup': {
                from: "organizer",
                localField: "organizer",
                foreignField: "organizerId",
                as: "ornrData"
            }},
        {$unwind: "$orgnData"},
        {$unwind: "$ornrData"},
        {$match: {'ornrData.city': 'Nagpur'}},

        {$skip: 0}, {$limit: 10}, 
        {$sort: {id: -1}}

    ], function (err, info) {
        res.json(info);
    });
});

from above code i am looking to get total rows count of result before limit. if anybody have an idea please let me know?

Siva Mandapati
  • 61
  • 2
  • 10
  • You are trying to get a "paging" count in the same query. Don't do that, it's pretty silly. There is a good explanation of "why" around somewhere I am sure. But it should not be too hard to work out you would need to stuff all of your results into an array in a single document just to get the count, then expand that out to "page". Just run a seperate pipeline to "count" and another for "results" in pages. It's How we've been working with database paging for years, and it does not change. – Blakes Seven Mar 26 '16 at 04:29
  • Thank you for spending your valuable time @ Blakes Seven – Siva Mandapati Mar 26 '16 at 05:09
  • I'm still spending it. I'm not really happy with the body of response on [Get a count of total documents with MongoDB when using limit](http://stackoverflow.com/a/21803405/2313887) but at least is does get to the point. I thought I did or someone else did make specific reference to the `$push` problem here, so I was still looking for the reference. But really, just run this one pipeline for the results and a simple `{ "_id": null, "count": { "$sum": 1 } }` for the total count without the "skip" and "limit". Still searching for the reference. – Blakes Seven Mar 26 '16 at 05:14
  • I'm also still work on that to get a count of total documents when using limit. i tried { $group: { _id: null, count: { $sum: 1 } } } by using this i am getting only count but i want full data with count from collections. is there any process to getting data also through this? and one more thing is $group is takes more time to return the results also. please give me any suggestions. – Siva Mandapati Mar 26 '16 at 06:31

1 Answers1

-2

Add to the aggregate the following, removing limit:

{ $group: { _id: null, count: { $sum: 1 } } }
DiegoRBaquero
  • 1,208
  • 10
  • 14