Get a count of total documents with MongoDB when using limit












20














I am interested in optimizing a "pagination" solution I'm working on with MongoDB. My problem is straight forward. I usually limit the number of documents returned using the limit() functionality. This forces me to issue a redundant query without the limit() function in order for me to also capture the total number of documents in the query so I can pass to that to the client letting them know they'll have to issue an additional request(s) to retrieve the rest of the documents.



Is there a way to condense this into 1 query? Get the total number of documents but at the same time only retrieve a subset using limit()? Is there a different way to think about this problem than I am approaching it?










share|improve this question





























    20














    I am interested in optimizing a "pagination" solution I'm working on with MongoDB. My problem is straight forward. I usually limit the number of documents returned using the limit() functionality. This forces me to issue a redundant query without the limit() function in order for me to also capture the total number of documents in the query so I can pass to that to the client letting them know they'll have to issue an additional request(s) to retrieve the rest of the documents.



    Is there a way to condense this into 1 query? Get the total number of documents but at the same time only retrieve a subset using limit()? Is there a different way to think about this problem than I am approaching it?










    share|improve this question



























      20












      20








      20


      3





      I am interested in optimizing a "pagination" solution I'm working on with MongoDB. My problem is straight forward. I usually limit the number of documents returned using the limit() functionality. This forces me to issue a redundant query without the limit() function in order for me to also capture the total number of documents in the query so I can pass to that to the client letting them know they'll have to issue an additional request(s) to retrieve the rest of the documents.



      Is there a way to condense this into 1 query? Get the total number of documents but at the same time only retrieve a subset using limit()? Is there a different way to think about this problem than I am approaching it?










      share|improve this question















      I am interested in optimizing a "pagination" solution I'm working on with MongoDB. My problem is straight forward. I usually limit the number of documents returned using the limit() functionality. This forces me to issue a redundant query without the limit() function in order for me to also capture the total number of documents in the query so I can pass to that to the client letting them know they'll have to issue an additional request(s) to retrieve the rest of the documents.



      Is there a way to condense this into 1 query? Get the total number of documents but at the same time only retrieve a subset using limit()? Is there a different way to think about this problem than I am approaching it?







      mongodb pagination mongodb-query aggregation-framework casbah






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 9 at 6:01









      Anthony Winzlet

      13.9k41239




      13.9k41239










      asked Feb 15 '14 at 20:33









      randombits

      11.2k55179348




      11.2k55179348
























          9 Answers
          9






          active

          oldest

          votes


















          13














          No, there is no other way. Two queries - one for count - one with limit. Or you have to use a different database. Apache Solr for instance works like you want. Every query there is limited and returns totalCount.






          share|improve this answer



















          • 1




            I'm not sure if "No" is quite the answer anymore now that we have mongoDb 3.4. See stackoverflow.com/a/39784851/3654061
            – Felipe
            Feb 13 at 5:18








          • 1




            There are multiple ways of doing this as I've been search for a solution myself. You can create an aggregation operation to return the total count as well as full documents according to a condition. You can also do one findAll based on conditions. Store the length of that array. And then slice out values according to your limit / offset values. Both of these options are only one call to the DB. The expense of the aggregation depends on how complex it is, same with the slice that you run on the returned array. Thoughts on this?
            – Sam Gruse
            Dec 7 at 5:24





















          5














          there is a way in Mongodb 3.4: $facet



          you can do



          db.collection.aggregate([
          {
          $facet: {
          data: [{ $match: {} }],
          total: { $count: 'total' }
          }
          }
          ])


          then you will be able to run two aggregate at the same time






          share|improve this answer

















          • 1




            Just little update total should be an array like total: [{ $count: 'total' }]
            – Sunil Pachlangia
            Sep 7 at 13:32



















          3














          It all depends on the pagination experience you need as to whether or not you need to do two queries.



          Do you need to list every single page or even a range of pages? Does anyone even go to page 1051 - conceptually what does that actually mean?



          Theres been lots of UX on patterns of pagination - Avoid the pains of pagination covers various types of pagination and their scenarios and many don't need a count query to know if theres a next page. For example if you display 10 items on a page and you limit to 13 - you'll know if theres another page..






          share|improve this answer





























            3














            Times have changed, and I believe you can achieve what the OP is asking by using aggregation with $sort, $group and $project. For my system, I needed to also grab some user info from my users collection. Hopefully this can answer any questions around that as well. Below is an aggregation pipe. The last three objects (sort, group and project) are what handle getting the total count, then providing pagination capabilities.



            db.posts.aggregate([
            { $match: { public: true },
            { $lookup: {
            from: 'users',
            localField: 'userId',
            foreignField: 'userId',
            as: 'userInfo'
            } },
            { $project: {
            postId: 1,
            title: 1,
            description: 1
            updated: 1,
            userInfo: {
            $let: {
            vars: {
            firstUser: {
            $arrayElemAt: ['$userInfo', 0]
            }
            },
            in: {
            username: '$$firstUser.username'
            }
            }
            }
            } },
            { $sort: { updated: -1 } },
            { $group: {
            _id: null,
            postCount: { $sum: 1 },
            posts: {
            $push: '$$ROOT'
            }
            } },
            { $project: {
            _id: 0,
            postCount: 1,
            posts: {
            $slice: [
            '$posts',
            currentPage ? (currentPage - 1) * RESULTS_PER_PAGE : 0,
            RESULTS_PER_PAGE
            ]
            }
            } }
            ])





            share|improve this answer





















            • What will be the response for this query. Will it return count as well as result
              – Kumar
              Sep 7 '17 at 6:57










            • @Kumar yes, the count is calculated during $group using $sum and the array result comes from $push. You can see in the $project that I include the post count (postCount) then take only a section from the result array using $slice. The final response returns the number of total posts along with only a section of them for pagination.
              – TestWell
              Sep 8 '17 at 16:37



















            2














            Mongodb 3.4 has introduced $facet aggregation




            which processes multiple aggregation pipelines within a single stage
            on the same set of input documents.




            Using $facet and $group you can find documents with $limit and can get total count.



            You can use below aggregation in mongodb 3.4



            db.collection.aggregate([
            { "$facet": {
            "totalData": [
            { "$match": { }},
            { "$skip": 10 },
            { "$limit": 10 }
            ],
            "totalCount": [
            { "$group": {
            "_id": null,
            "count": { "$sum": 1 }
            }}
            ]
            }}
            ])


            Even you can use $count aggregation which has been introduced in mongodb 3.6.



            You can use below aggregation in mongodb 3.6



            db.collection.aggregate([
            { "$facet": {
            "totalData": [
            { "$match": { }},
            { "$skip": 10 },
            { "$limit": 10 }
            ],
            "totalCount": [
            { "$count": "count" }
            ]
            }}
            ])





            share|improve this answer































              0














              You can do this in one query. First you run a count and within that run the limit() function.



              In Node.js and Express.js, you will have to use it like this to be able to use the "count" function along with the toArray's "result".



              var curFind = db.collection('tasks').find({query});


              Then you can run two functions after it like this (one nested in the other)



              curFind.count(function (e, count) {

              // Use count here

              curFind.skip(0).limit(10).toArray(function(err, result) {

              // Use result here and count here

              });

              });





              share|improve this answer























              • This is not correct method.You are just finding in all document instead of first 10 documents in each request.For each request,everytime you are just finding in whole documents. not in first 10.
                – Udit Kumawat
                Apr 29 '17 at 6:29










              • thanks for the comment. at the time this is a solution we came up with. it may not be perfect when it comes to efficiency. do suggest a solution to improvise.
                – 0112358
                Apr 30 '17 at 6:52



















              0














              It is possible to get the total result size without the effect of limit() using count() as answered here:
              Limiting results in MongoDB but still getting the full count?



              According to the documentation you can even control whether limit/pagination is taken into account when calling count():
              https://docs.mongodb.com/manual/reference/method/cursor.count/#cursor.count



              Edit: in contrast to what is written elsewhere - the docs clearly state that "The operation does not perform the query but instead counts the results that would be returned by the query". Which - from my understanding - means that only one query is executed.



              Example:



              > db.createCollection("test")
              { "ok" : 1 }

              > db.test.insert([{name: "first"}, {name: "second"}, {name: "third"},
              {name: "forth"}, {name: "fifth"}])
              BulkWriteResult({
              "writeErrors" : [ ],
              "writeConcernErrors" : [ ],
              "nInserted" : 5,
              "nUpserted" : 0,
              "nMatched" : 0,
              "nModified" : 0,
              "nRemoved" : 0,
              "upserted" : [ ]
              })

              > db.test.find()
              { "_id" : ObjectId("58ff00918f5e60ff211521c5"), "name" : "first" }
              { "_id" : ObjectId("58ff00918f5e60ff211521c6"), "name" : "second" }
              { "_id" : ObjectId("58ff00918f5e60ff211521c7"), "name" : "third" }
              { "_id" : ObjectId("58ff00918f5e60ff211521c8"), "name" : "forth" }
              { "_id" : ObjectId("58ff00918f5e60ff211521c9"), "name" : "fifth" }

              > db.test.count()
              5

              > var result = db.test.find().limit(3)
              > result
              { "_id" : ObjectId("58ff00918f5e60ff211521c5"), "name" : "first" }
              { "_id" : ObjectId("58ff00918f5e60ff211521c6"), "name" : "second" }
              { "_id" : ObjectId("58ff00918f5e60ff211521c7"), "name" : "third" }

              > result.count()
              5 (total result size of the query without limit)

              > result.count(1)
              3 (result size with limit(3) taken into account)





              share|improve this answer























              • If you downvote, please add a reason so I have the chance to understand - which might also improve future answers!
                – mrechtien
                Apr 25 '17 at 14:12






              • 1




                I'm not sure about the downvote but just an FYI: count() only works with find() and thus is not helpful with aggregate queries
                – Felipe
                Feb 13 at 5:01



















              0














              Try as bellow:




              cursor.count(false, function(err, total){ console.log("total", total) })




              core.db.users.find(query, {}, {skip:0, limit:1}, function(err, cursor){
              if(err)
              return callback(err);

              cursor.toArray(function(err, items){
              if(err)
              return callback(err);

              cursor.count(false, function(err, total){
              if(err)
              return callback(err);

              console.log("cursor", total)

              callback(null, {items: items, total:total})
              })
              })
              })





              share|improve this answer





























                0














                MongoDB allows you to use cursor.count() even when you pass limit() or skip().



                Lets say you have a db.collection with 10 items.



                You can do:



                async function getQuery() {
                let query = await db.collection.find({}).skip(5).limit(5); // returns last 5 items in db
                let countTotal = await query.count() // returns 10-- will not take `skip` or `limit` into consideration
                let countWithConstraints = await query.count(true) // returns 5 -- will take into consideration `skip` and `limit`
                return { query, countTotal }
                }





                share|improve this answer























                • how about aggregate ?
                  – Mahmoud Heretani
                  Jul 3 at 18:23











                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f21803290%2fget-a-count-of-total-documents-with-mongodb-when-using-limit%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                9 Answers
                9






                active

                oldest

                votes








                9 Answers
                9






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                13














                No, there is no other way. Two queries - one for count - one with limit. Or you have to use a different database. Apache Solr for instance works like you want. Every query there is limited and returns totalCount.






                share|improve this answer



















                • 1




                  I'm not sure if "No" is quite the answer anymore now that we have mongoDb 3.4. See stackoverflow.com/a/39784851/3654061
                  – Felipe
                  Feb 13 at 5:18








                • 1




                  There are multiple ways of doing this as I've been search for a solution myself. You can create an aggregation operation to return the total count as well as full documents according to a condition. You can also do one findAll based on conditions. Store the length of that array. And then slice out values according to your limit / offset values. Both of these options are only one call to the DB. The expense of the aggregation depends on how complex it is, same with the slice that you run on the returned array. Thoughts on this?
                  – Sam Gruse
                  Dec 7 at 5:24


















                13














                No, there is no other way. Two queries - one for count - one with limit. Or you have to use a different database. Apache Solr for instance works like you want. Every query there is limited and returns totalCount.






                share|improve this answer



















                • 1




                  I'm not sure if "No" is quite the answer anymore now that we have mongoDb 3.4. See stackoverflow.com/a/39784851/3654061
                  – Felipe
                  Feb 13 at 5:18








                • 1




                  There are multiple ways of doing this as I've been search for a solution myself. You can create an aggregation operation to return the total count as well as full documents according to a condition. You can also do one findAll based on conditions. Store the length of that array. And then slice out values according to your limit / offset values. Both of these options are only one call to the DB. The expense of the aggregation depends on how complex it is, same with the slice that you run on the returned array. Thoughts on this?
                  – Sam Gruse
                  Dec 7 at 5:24
















                13












                13








                13






                No, there is no other way. Two queries - one for count - one with limit. Or you have to use a different database. Apache Solr for instance works like you want. Every query there is limited and returns totalCount.






                share|improve this answer














                No, there is no other way. Two queries - one for count - one with limit. Or you have to use a different database. Apache Solr for instance works like you want. Every query there is limited and returns totalCount.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 8 '15 at 8:58

























                answered Feb 15 '14 at 20:44









                heinob

                5,43823052




                5,43823052








                • 1




                  I'm not sure if "No" is quite the answer anymore now that we have mongoDb 3.4. See stackoverflow.com/a/39784851/3654061
                  – Felipe
                  Feb 13 at 5:18








                • 1




                  There are multiple ways of doing this as I've been search for a solution myself. You can create an aggregation operation to return the total count as well as full documents according to a condition. You can also do one findAll based on conditions. Store the length of that array. And then slice out values according to your limit / offset values. Both of these options are only one call to the DB. The expense of the aggregation depends on how complex it is, same with the slice that you run on the returned array. Thoughts on this?
                  – Sam Gruse
                  Dec 7 at 5:24
















                • 1




                  I'm not sure if "No" is quite the answer anymore now that we have mongoDb 3.4. See stackoverflow.com/a/39784851/3654061
                  – Felipe
                  Feb 13 at 5:18








                • 1




                  There are multiple ways of doing this as I've been search for a solution myself. You can create an aggregation operation to return the total count as well as full documents according to a condition. You can also do one findAll based on conditions. Store the length of that array. And then slice out values according to your limit / offset values. Both of these options are only one call to the DB. The expense of the aggregation depends on how complex it is, same with the slice that you run on the returned array. Thoughts on this?
                  – Sam Gruse
                  Dec 7 at 5:24










                1




                1




                I'm not sure if "No" is quite the answer anymore now that we have mongoDb 3.4. See stackoverflow.com/a/39784851/3654061
                – Felipe
                Feb 13 at 5:18






                I'm not sure if "No" is quite the answer anymore now that we have mongoDb 3.4. See stackoverflow.com/a/39784851/3654061
                – Felipe
                Feb 13 at 5:18






                1




                1




                There are multiple ways of doing this as I've been search for a solution myself. You can create an aggregation operation to return the total count as well as full documents according to a condition. You can also do one findAll based on conditions. Store the length of that array. And then slice out values according to your limit / offset values. Both of these options are only one call to the DB. The expense of the aggregation depends on how complex it is, same with the slice that you run on the returned array. Thoughts on this?
                – Sam Gruse
                Dec 7 at 5:24






                There are multiple ways of doing this as I've been search for a solution myself. You can create an aggregation operation to return the total count as well as full documents according to a condition. You can also do one findAll based on conditions. Store the length of that array. And then slice out values according to your limit / offset values. Both of these options are only one call to the DB. The expense of the aggregation depends on how complex it is, same with the slice that you run on the returned array. Thoughts on this?
                – Sam Gruse
                Dec 7 at 5:24















                5














                there is a way in Mongodb 3.4: $facet



                you can do



                db.collection.aggregate([
                {
                $facet: {
                data: [{ $match: {} }],
                total: { $count: 'total' }
                }
                }
                ])


                then you will be able to run two aggregate at the same time






                share|improve this answer

















                • 1




                  Just little update total should be an array like total: [{ $count: 'total' }]
                  – Sunil Pachlangia
                  Sep 7 at 13:32
















                5














                there is a way in Mongodb 3.4: $facet



                you can do



                db.collection.aggregate([
                {
                $facet: {
                data: [{ $match: {} }],
                total: { $count: 'total' }
                }
                }
                ])


                then you will be able to run two aggregate at the same time






                share|improve this answer

















                • 1




                  Just little update total should be an array like total: [{ $count: 'total' }]
                  – Sunil Pachlangia
                  Sep 7 at 13:32














                5












                5








                5






                there is a way in Mongodb 3.4: $facet



                you can do



                db.collection.aggregate([
                {
                $facet: {
                data: [{ $match: {} }],
                total: { $count: 'total' }
                }
                }
                ])


                then you will be able to run two aggregate at the same time






                share|improve this answer












                there is a way in Mongodb 3.4: $facet



                you can do



                db.collection.aggregate([
                {
                $facet: {
                data: [{ $match: {} }],
                total: { $count: 'total' }
                }
                }
                ])


                then you will be able to run two aggregate at the same time







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Oct 15 '17 at 17:17









                Matthew

                5113




                5113








                • 1




                  Just little update total should be an array like total: [{ $count: 'total' }]
                  – Sunil Pachlangia
                  Sep 7 at 13:32














                • 1




                  Just little update total should be an array like total: [{ $count: 'total' }]
                  – Sunil Pachlangia
                  Sep 7 at 13:32








                1




                1




                Just little update total should be an array like total: [{ $count: 'total' }]
                – Sunil Pachlangia
                Sep 7 at 13:32




                Just little update total should be an array like total: [{ $count: 'total' }]
                – Sunil Pachlangia
                Sep 7 at 13:32











                3














                It all depends on the pagination experience you need as to whether or not you need to do two queries.



                Do you need to list every single page or even a range of pages? Does anyone even go to page 1051 - conceptually what does that actually mean?



                Theres been lots of UX on patterns of pagination - Avoid the pains of pagination covers various types of pagination and their scenarios and many don't need a count query to know if theres a next page. For example if you display 10 items on a page and you limit to 13 - you'll know if theres another page..






                share|improve this answer


























                  3














                  It all depends on the pagination experience you need as to whether or not you need to do two queries.



                  Do you need to list every single page or even a range of pages? Does anyone even go to page 1051 - conceptually what does that actually mean?



                  Theres been lots of UX on patterns of pagination - Avoid the pains of pagination covers various types of pagination and their scenarios and many don't need a count query to know if theres a next page. For example if you display 10 items on a page and you limit to 13 - you'll know if theres another page..






                  share|improve this answer
























                    3












                    3








                    3






                    It all depends on the pagination experience you need as to whether or not you need to do two queries.



                    Do you need to list every single page or even a range of pages? Does anyone even go to page 1051 - conceptually what does that actually mean?



                    Theres been lots of UX on patterns of pagination - Avoid the pains of pagination covers various types of pagination and their scenarios and many don't need a count query to know if theres a next page. For example if you display 10 items on a page and you limit to 13 - you'll know if theres another page..






                    share|improve this answer












                    It all depends on the pagination experience you need as to whether or not you need to do two queries.



                    Do you need to list every single page or even a range of pages? Does anyone even go to page 1051 - conceptually what does that actually mean?



                    Theres been lots of UX on patterns of pagination - Avoid the pains of pagination covers various types of pagination and their scenarios and many don't need a count query to know if theres a next page. For example if you display 10 items on a page and you limit to 13 - you'll know if theres another page..







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Feb 17 '14 at 9:21









                    Ross

                    14.5k13359




                    14.5k13359























                        3














                        Times have changed, and I believe you can achieve what the OP is asking by using aggregation with $sort, $group and $project. For my system, I needed to also grab some user info from my users collection. Hopefully this can answer any questions around that as well. Below is an aggregation pipe. The last three objects (sort, group and project) are what handle getting the total count, then providing pagination capabilities.



                        db.posts.aggregate([
                        { $match: { public: true },
                        { $lookup: {
                        from: 'users',
                        localField: 'userId',
                        foreignField: 'userId',
                        as: 'userInfo'
                        } },
                        { $project: {
                        postId: 1,
                        title: 1,
                        description: 1
                        updated: 1,
                        userInfo: {
                        $let: {
                        vars: {
                        firstUser: {
                        $arrayElemAt: ['$userInfo', 0]
                        }
                        },
                        in: {
                        username: '$$firstUser.username'
                        }
                        }
                        }
                        } },
                        { $sort: { updated: -1 } },
                        { $group: {
                        _id: null,
                        postCount: { $sum: 1 },
                        posts: {
                        $push: '$$ROOT'
                        }
                        } },
                        { $project: {
                        _id: 0,
                        postCount: 1,
                        posts: {
                        $slice: [
                        '$posts',
                        currentPage ? (currentPage - 1) * RESULTS_PER_PAGE : 0,
                        RESULTS_PER_PAGE
                        ]
                        }
                        } }
                        ])





                        share|improve this answer





















                        • What will be the response for this query. Will it return count as well as result
                          – Kumar
                          Sep 7 '17 at 6:57










                        • @Kumar yes, the count is calculated during $group using $sum and the array result comes from $push. You can see in the $project that I include the post count (postCount) then take only a section from the result array using $slice. The final response returns the number of total posts along with only a section of them for pagination.
                          – TestWell
                          Sep 8 '17 at 16:37
















                        3














                        Times have changed, and I believe you can achieve what the OP is asking by using aggregation with $sort, $group and $project. For my system, I needed to also grab some user info from my users collection. Hopefully this can answer any questions around that as well. Below is an aggregation pipe. The last three objects (sort, group and project) are what handle getting the total count, then providing pagination capabilities.



                        db.posts.aggregate([
                        { $match: { public: true },
                        { $lookup: {
                        from: 'users',
                        localField: 'userId',
                        foreignField: 'userId',
                        as: 'userInfo'
                        } },
                        { $project: {
                        postId: 1,
                        title: 1,
                        description: 1
                        updated: 1,
                        userInfo: {
                        $let: {
                        vars: {
                        firstUser: {
                        $arrayElemAt: ['$userInfo', 0]
                        }
                        },
                        in: {
                        username: '$$firstUser.username'
                        }
                        }
                        }
                        } },
                        { $sort: { updated: -1 } },
                        { $group: {
                        _id: null,
                        postCount: { $sum: 1 },
                        posts: {
                        $push: '$$ROOT'
                        }
                        } },
                        { $project: {
                        _id: 0,
                        postCount: 1,
                        posts: {
                        $slice: [
                        '$posts',
                        currentPage ? (currentPage - 1) * RESULTS_PER_PAGE : 0,
                        RESULTS_PER_PAGE
                        ]
                        }
                        } }
                        ])





                        share|improve this answer





















                        • What will be the response for this query. Will it return count as well as result
                          – Kumar
                          Sep 7 '17 at 6:57










                        • @Kumar yes, the count is calculated during $group using $sum and the array result comes from $push. You can see in the $project that I include the post count (postCount) then take only a section from the result array using $slice. The final response returns the number of total posts along with only a section of them for pagination.
                          – TestWell
                          Sep 8 '17 at 16:37














                        3












                        3








                        3






                        Times have changed, and I believe you can achieve what the OP is asking by using aggregation with $sort, $group and $project. For my system, I needed to also grab some user info from my users collection. Hopefully this can answer any questions around that as well. Below is an aggregation pipe. The last three objects (sort, group and project) are what handle getting the total count, then providing pagination capabilities.



                        db.posts.aggregate([
                        { $match: { public: true },
                        { $lookup: {
                        from: 'users',
                        localField: 'userId',
                        foreignField: 'userId',
                        as: 'userInfo'
                        } },
                        { $project: {
                        postId: 1,
                        title: 1,
                        description: 1
                        updated: 1,
                        userInfo: {
                        $let: {
                        vars: {
                        firstUser: {
                        $arrayElemAt: ['$userInfo', 0]
                        }
                        },
                        in: {
                        username: '$$firstUser.username'
                        }
                        }
                        }
                        } },
                        { $sort: { updated: -1 } },
                        { $group: {
                        _id: null,
                        postCount: { $sum: 1 },
                        posts: {
                        $push: '$$ROOT'
                        }
                        } },
                        { $project: {
                        _id: 0,
                        postCount: 1,
                        posts: {
                        $slice: [
                        '$posts',
                        currentPage ? (currentPage - 1) * RESULTS_PER_PAGE : 0,
                        RESULTS_PER_PAGE
                        ]
                        }
                        } }
                        ])





                        share|improve this answer












                        Times have changed, and I believe you can achieve what the OP is asking by using aggregation with $sort, $group and $project. For my system, I needed to also grab some user info from my users collection. Hopefully this can answer any questions around that as well. Below is an aggregation pipe. The last three objects (sort, group and project) are what handle getting the total count, then providing pagination capabilities.



                        db.posts.aggregate([
                        { $match: { public: true },
                        { $lookup: {
                        from: 'users',
                        localField: 'userId',
                        foreignField: 'userId',
                        as: 'userInfo'
                        } },
                        { $project: {
                        postId: 1,
                        title: 1,
                        description: 1
                        updated: 1,
                        userInfo: {
                        $let: {
                        vars: {
                        firstUser: {
                        $arrayElemAt: ['$userInfo', 0]
                        }
                        },
                        in: {
                        username: '$$firstUser.username'
                        }
                        }
                        }
                        } },
                        { $sort: { updated: -1 } },
                        { $group: {
                        _id: null,
                        postCount: { $sum: 1 },
                        posts: {
                        $push: '$$ROOT'
                        }
                        } },
                        { $project: {
                        _id: 0,
                        postCount: 1,
                        posts: {
                        $slice: [
                        '$posts',
                        currentPage ? (currentPage - 1) * RESULTS_PER_PAGE : 0,
                        RESULTS_PER_PAGE
                        ]
                        }
                        } }
                        ])






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jul 1 '17 at 6:24









                        TestWell

                        354316




                        354316












                        • What will be the response for this query. Will it return count as well as result
                          – Kumar
                          Sep 7 '17 at 6:57










                        • @Kumar yes, the count is calculated during $group using $sum and the array result comes from $push. You can see in the $project that I include the post count (postCount) then take only a section from the result array using $slice. The final response returns the number of total posts along with only a section of them for pagination.
                          – TestWell
                          Sep 8 '17 at 16:37


















                        • What will be the response for this query. Will it return count as well as result
                          – Kumar
                          Sep 7 '17 at 6:57










                        • @Kumar yes, the count is calculated during $group using $sum and the array result comes from $push. You can see in the $project that I include the post count (postCount) then take only a section from the result array using $slice. The final response returns the number of total posts along with only a section of them for pagination.
                          – TestWell
                          Sep 8 '17 at 16:37
















                        What will be the response for this query. Will it return count as well as result
                        – Kumar
                        Sep 7 '17 at 6:57




                        What will be the response for this query. Will it return count as well as result
                        – Kumar
                        Sep 7 '17 at 6:57












                        @Kumar yes, the count is calculated during $group using $sum and the array result comes from $push. You can see in the $project that I include the post count (postCount) then take only a section from the result array using $slice. The final response returns the number of total posts along with only a section of them for pagination.
                        – TestWell
                        Sep 8 '17 at 16:37




                        @Kumar yes, the count is calculated during $group using $sum and the array result comes from $push. You can see in the $project that I include the post count (postCount) then take only a section from the result array using $slice. The final response returns the number of total posts along with only a section of them for pagination.
                        – TestWell
                        Sep 8 '17 at 16:37











                        2














                        Mongodb 3.4 has introduced $facet aggregation




                        which processes multiple aggregation pipelines within a single stage
                        on the same set of input documents.




                        Using $facet and $group you can find documents with $limit and can get total count.



                        You can use below aggregation in mongodb 3.4



                        db.collection.aggregate([
                        { "$facet": {
                        "totalData": [
                        { "$match": { }},
                        { "$skip": 10 },
                        { "$limit": 10 }
                        ],
                        "totalCount": [
                        { "$group": {
                        "_id": null,
                        "count": { "$sum": 1 }
                        }}
                        ]
                        }}
                        ])


                        Even you can use $count aggregation which has been introduced in mongodb 3.6.



                        You can use below aggregation in mongodb 3.6



                        db.collection.aggregate([
                        { "$facet": {
                        "totalData": [
                        { "$match": { }},
                        { "$skip": 10 },
                        { "$limit": 10 }
                        ],
                        "totalCount": [
                        { "$count": "count" }
                        ]
                        }}
                        ])





                        share|improve this answer




























                          2














                          Mongodb 3.4 has introduced $facet aggregation




                          which processes multiple aggregation pipelines within a single stage
                          on the same set of input documents.




                          Using $facet and $group you can find documents with $limit and can get total count.



                          You can use below aggregation in mongodb 3.4



                          db.collection.aggregate([
                          { "$facet": {
                          "totalData": [
                          { "$match": { }},
                          { "$skip": 10 },
                          { "$limit": 10 }
                          ],
                          "totalCount": [
                          { "$group": {
                          "_id": null,
                          "count": { "$sum": 1 }
                          }}
                          ]
                          }}
                          ])


                          Even you can use $count aggregation which has been introduced in mongodb 3.6.



                          You can use below aggregation in mongodb 3.6



                          db.collection.aggregate([
                          { "$facet": {
                          "totalData": [
                          { "$match": { }},
                          { "$skip": 10 },
                          { "$limit": 10 }
                          ],
                          "totalCount": [
                          { "$count": "count" }
                          ]
                          }}
                          ])





                          share|improve this answer


























                            2












                            2








                            2






                            Mongodb 3.4 has introduced $facet aggregation




                            which processes multiple aggregation pipelines within a single stage
                            on the same set of input documents.




                            Using $facet and $group you can find documents with $limit and can get total count.



                            You can use below aggregation in mongodb 3.4



                            db.collection.aggregate([
                            { "$facet": {
                            "totalData": [
                            { "$match": { }},
                            { "$skip": 10 },
                            { "$limit": 10 }
                            ],
                            "totalCount": [
                            { "$group": {
                            "_id": null,
                            "count": { "$sum": 1 }
                            }}
                            ]
                            }}
                            ])


                            Even you can use $count aggregation which has been introduced in mongodb 3.6.



                            You can use below aggregation in mongodb 3.6



                            db.collection.aggregate([
                            { "$facet": {
                            "totalData": [
                            { "$match": { }},
                            { "$skip": 10 },
                            { "$limit": 10 }
                            ],
                            "totalCount": [
                            { "$count": "count" }
                            ]
                            }}
                            ])





                            share|improve this answer














                            Mongodb 3.4 has introduced $facet aggregation




                            which processes multiple aggregation pipelines within a single stage
                            on the same set of input documents.




                            Using $facet and $group you can find documents with $limit and can get total count.



                            You can use below aggregation in mongodb 3.4



                            db.collection.aggregate([
                            { "$facet": {
                            "totalData": [
                            { "$match": { }},
                            { "$skip": 10 },
                            { "$limit": 10 }
                            ],
                            "totalCount": [
                            { "$group": {
                            "_id": null,
                            "count": { "$sum": 1 }
                            }}
                            ]
                            }}
                            ])


                            Even you can use $count aggregation which has been introduced in mongodb 3.6.



                            You can use below aggregation in mongodb 3.6



                            db.collection.aggregate([
                            { "$facet": {
                            "totalData": [
                            { "$match": { }},
                            { "$skip": 10 },
                            { "$limit": 10 }
                            ],
                            "totalCount": [
                            { "$count": "count" }
                            ]
                            }}
                            ])






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 9 at 11:51

























                            answered Nov 9 at 6:00









                            Anthony Winzlet

                            13.9k41239




                            13.9k41239























                                0














                                You can do this in one query. First you run a count and within that run the limit() function.



                                In Node.js and Express.js, you will have to use it like this to be able to use the "count" function along with the toArray's "result".



                                var curFind = db.collection('tasks').find({query});


                                Then you can run two functions after it like this (one nested in the other)



                                curFind.count(function (e, count) {

                                // Use count here

                                curFind.skip(0).limit(10).toArray(function(err, result) {

                                // Use result here and count here

                                });

                                });





                                share|improve this answer























                                • This is not correct method.You are just finding in all document instead of first 10 documents in each request.For each request,everytime you are just finding in whole documents. not in first 10.
                                  – Udit Kumawat
                                  Apr 29 '17 at 6:29










                                • thanks for the comment. at the time this is a solution we came up with. it may not be perfect when it comes to efficiency. do suggest a solution to improvise.
                                  – 0112358
                                  Apr 30 '17 at 6:52
















                                0














                                You can do this in one query. First you run a count and within that run the limit() function.



                                In Node.js and Express.js, you will have to use it like this to be able to use the "count" function along with the toArray's "result".



                                var curFind = db.collection('tasks').find({query});


                                Then you can run two functions after it like this (one nested in the other)



                                curFind.count(function (e, count) {

                                // Use count here

                                curFind.skip(0).limit(10).toArray(function(err, result) {

                                // Use result here and count here

                                });

                                });





                                share|improve this answer























                                • This is not correct method.You are just finding in all document instead of first 10 documents in each request.For each request,everytime you are just finding in whole documents. not in first 10.
                                  – Udit Kumawat
                                  Apr 29 '17 at 6:29










                                • thanks for the comment. at the time this is a solution we came up with. it may not be perfect when it comes to efficiency. do suggest a solution to improvise.
                                  – 0112358
                                  Apr 30 '17 at 6:52














                                0












                                0








                                0






                                You can do this in one query. First you run a count and within that run the limit() function.



                                In Node.js and Express.js, you will have to use it like this to be able to use the "count" function along with the toArray's "result".



                                var curFind = db.collection('tasks').find({query});


                                Then you can run two functions after it like this (one nested in the other)



                                curFind.count(function (e, count) {

                                // Use count here

                                curFind.skip(0).limit(10).toArray(function(err, result) {

                                // Use result here and count here

                                });

                                });





                                share|improve this answer














                                You can do this in one query. First you run a count and within that run the limit() function.



                                In Node.js and Express.js, you will have to use it like this to be able to use the "count" function along with the toArray's "result".



                                var curFind = db.collection('tasks').find({query});


                                Then you can run two functions after it like this (one nested in the other)



                                curFind.count(function (e, count) {

                                // Use count here

                                curFind.skip(0).limit(10).toArray(function(err, result) {

                                // Use result here and count here

                                });

                                });






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Sep 4 '16 at 23:09

























                                answered Sep 4 '16 at 22:59









                                0112358

                                11118




                                11118












                                • This is not correct method.You are just finding in all document instead of first 10 documents in each request.For each request,everytime you are just finding in whole documents. not in first 10.
                                  – Udit Kumawat
                                  Apr 29 '17 at 6:29










                                • thanks for the comment. at the time this is a solution we came up with. it may not be perfect when it comes to efficiency. do suggest a solution to improvise.
                                  – 0112358
                                  Apr 30 '17 at 6:52


















                                • This is not correct method.You are just finding in all document instead of first 10 documents in each request.For each request,everytime you are just finding in whole documents. not in first 10.
                                  – Udit Kumawat
                                  Apr 29 '17 at 6:29










                                • thanks for the comment. at the time this is a solution we came up with. it may not be perfect when it comes to efficiency. do suggest a solution to improvise.
                                  – 0112358
                                  Apr 30 '17 at 6:52
















                                This is not correct method.You are just finding in all document instead of first 10 documents in each request.For each request,everytime you are just finding in whole documents. not in first 10.
                                – Udit Kumawat
                                Apr 29 '17 at 6:29




                                This is not correct method.You are just finding in all document instead of first 10 documents in each request.For each request,everytime you are just finding in whole documents. not in first 10.
                                – Udit Kumawat
                                Apr 29 '17 at 6:29












                                thanks for the comment. at the time this is a solution we came up with. it may not be perfect when it comes to efficiency. do suggest a solution to improvise.
                                – 0112358
                                Apr 30 '17 at 6:52




                                thanks for the comment. at the time this is a solution we came up with. it may not be perfect when it comes to efficiency. do suggest a solution to improvise.
                                – 0112358
                                Apr 30 '17 at 6:52











                                0














                                It is possible to get the total result size without the effect of limit() using count() as answered here:
                                Limiting results in MongoDB but still getting the full count?



                                According to the documentation you can even control whether limit/pagination is taken into account when calling count():
                                https://docs.mongodb.com/manual/reference/method/cursor.count/#cursor.count



                                Edit: in contrast to what is written elsewhere - the docs clearly state that "The operation does not perform the query but instead counts the results that would be returned by the query". Which - from my understanding - means that only one query is executed.



                                Example:



                                > db.createCollection("test")
                                { "ok" : 1 }

                                > db.test.insert([{name: "first"}, {name: "second"}, {name: "third"},
                                {name: "forth"}, {name: "fifth"}])
                                BulkWriteResult({
                                "writeErrors" : [ ],
                                "writeConcernErrors" : [ ],
                                "nInserted" : 5,
                                "nUpserted" : 0,
                                "nMatched" : 0,
                                "nModified" : 0,
                                "nRemoved" : 0,
                                "upserted" : [ ]
                                })

                                > db.test.find()
                                { "_id" : ObjectId("58ff00918f5e60ff211521c5"), "name" : "first" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c6"), "name" : "second" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c7"), "name" : "third" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c8"), "name" : "forth" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c9"), "name" : "fifth" }

                                > db.test.count()
                                5

                                > var result = db.test.find().limit(3)
                                > result
                                { "_id" : ObjectId("58ff00918f5e60ff211521c5"), "name" : "first" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c6"), "name" : "second" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c7"), "name" : "third" }

                                > result.count()
                                5 (total result size of the query without limit)

                                > result.count(1)
                                3 (result size with limit(3) taken into account)





                                share|improve this answer























                                • If you downvote, please add a reason so I have the chance to understand - which might also improve future answers!
                                  – mrechtien
                                  Apr 25 '17 at 14:12






                                • 1




                                  I'm not sure about the downvote but just an FYI: count() only works with find() and thus is not helpful with aggregate queries
                                  – Felipe
                                  Feb 13 at 5:01
















                                0














                                It is possible to get the total result size without the effect of limit() using count() as answered here:
                                Limiting results in MongoDB but still getting the full count?



                                According to the documentation you can even control whether limit/pagination is taken into account when calling count():
                                https://docs.mongodb.com/manual/reference/method/cursor.count/#cursor.count



                                Edit: in contrast to what is written elsewhere - the docs clearly state that "The operation does not perform the query but instead counts the results that would be returned by the query". Which - from my understanding - means that only one query is executed.



                                Example:



                                > db.createCollection("test")
                                { "ok" : 1 }

                                > db.test.insert([{name: "first"}, {name: "second"}, {name: "third"},
                                {name: "forth"}, {name: "fifth"}])
                                BulkWriteResult({
                                "writeErrors" : [ ],
                                "writeConcernErrors" : [ ],
                                "nInserted" : 5,
                                "nUpserted" : 0,
                                "nMatched" : 0,
                                "nModified" : 0,
                                "nRemoved" : 0,
                                "upserted" : [ ]
                                })

                                > db.test.find()
                                { "_id" : ObjectId("58ff00918f5e60ff211521c5"), "name" : "first" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c6"), "name" : "second" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c7"), "name" : "third" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c8"), "name" : "forth" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c9"), "name" : "fifth" }

                                > db.test.count()
                                5

                                > var result = db.test.find().limit(3)
                                > result
                                { "_id" : ObjectId("58ff00918f5e60ff211521c5"), "name" : "first" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c6"), "name" : "second" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c7"), "name" : "third" }

                                > result.count()
                                5 (total result size of the query without limit)

                                > result.count(1)
                                3 (result size with limit(3) taken into account)





                                share|improve this answer























                                • If you downvote, please add a reason so I have the chance to understand - which might also improve future answers!
                                  – mrechtien
                                  Apr 25 '17 at 14:12






                                • 1




                                  I'm not sure about the downvote but just an FYI: count() only works with find() and thus is not helpful with aggregate queries
                                  – Felipe
                                  Feb 13 at 5:01














                                0












                                0








                                0






                                It is possible to get the total result size without the effect of limit() using count() as answered here:
                                Limiting results in MongoDB but still getting the full count?



                                According to the documentation you can even control whether limit/pagination is taken into account when calling count():
                                https://docs.mongodb.com/manual/reference/method/cursor.count/#cursor.count



                                Edit: in contrast to what is written elsewhere - the docs clearly state that "The operation does not perform the query but instead counts the results that would be returned by the query". Which - from my understanding - means that only one query is executed.



                                Example:



                                > db.createCollection("test")
                                { "ok" : 1 }

                                > db.test.insert([{name: "first"}, {name: "second"}, {name: "third"},
                                {name: "forth"}, {name: "fifth"}])
                                BulkWriteResult({
                                "writeErrors" : [ ],
                                "writeConcernErrors" : [ ],
                                "nInserted" : 5,
                                "nUpserted" : 0,
                                "nMatched" : 0,
                                "nModified" : 0,
                                "nRemoved" : 0,
                                "upserted" : [ ]
                                })

                                > db.test.find()
                                { "_id" : ObjectId("58ff00918f5e60ff211521c5"), "name" : "first" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c6"), "name" : "second" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c7"), "name" : "third" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c8"), "name" : "forth" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c9"), "name" : "fifth" }

                                > db.test.count()
                                5

                                > var result = db.test.find().limit(3)
                                > result
                                { "_id" : ObjectId("58ff00918f5e60ff211521c5"), "name" : "first" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c6"), "name" : "second" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c7"), "name" : "third" }

                                > result.count()
                                5 (total result size of the query without limit)

                                > result.count(1)
                                3 (result size with limit(3) taken into account)





                                share|improve this answer














                                It is possible to get the total result size without the effect of limit() using count() as answered here:
                                Limiting results in MongoDB but still getting the full count?



                                According to the documentation you can even control whether limit/pagination is taken into account when calling count():
                                https://docs.mongodb.com/manual/reference/method/cursor.count/#cursor.count



                                Edit: in contrast to what is written elsewhere - the docs clearly state that "The operation does not perform the query but instead counts the results that would be returned by the query". Which - from my understanding - means that only one query is executed.



                                Example:



                                > db.createCollection("test")
                                { "ok" : 1 }

                                > db.test.insert([{name: "first"}, {name: "second"}, {name: "third"},
                                {name: "forth"}, {name: "fifth"}])
                                BulkWriteResult({
                                "writeErrors" : [ ],
                                "writeConcernErrors" : [ ],
                                "nInserted" : 5,
                                "nUpserted" : 0,
                                "nMatched" : 0,
                                "nModified" : 0,
                                "nRemoved" : 0,
                                "upserted" : [ ]
                                })

                                > db.test.find()
                                { "_id" : ObjectId("58ff00918f5e60ff211521c5"), "name" : "first" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c6"), "name" : "second" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c7"), "name" : "third" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c8"), "name" : "forth" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c9"), "name" : "fifth" }

                                > db.test.count()
                                5

                                > var result = db.test.find().limit(3)
                                > result
                                { "_id" : ObjectId("58ff00918f5e60ff211521c5"), "name" : "first" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c6"), "name" : "second" }
                                { "_id" : ObjectId("58ff00918f5e60ff211521c7"), "name" : "third" }

                                > result.count()
                                5 (total result size of the query without limit)

                                > result.count(1)
                                3 (result size with limit(3) taken into account)






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited May 23 '17 at 12:18









                                Community

                                11




                                11










                                answered Apr 21 '17 at 10:12









                                mrechtien

                                354




                                354












                                • If you downvote, please add a reason so I have the chance to understand - which might also improve future answers!
                                  – mrechtien
                                  Apr 25 '17 at 14:12






                                • 1




                                  I'm not sure about the downvote but just an FYI: count() only works with find() and thus is not helpful with aggregate queries
                                  – Felipe
                                  Feb 13 at 5:01


















                                • If you downvote, please add a reason so I have the chance to understand - which might also improve future answers!
                                  – mrechtien
                                  Apr 25 '17 at 14:12






                                • 1




                                  I'm not sure about the downvote but just an FYI: count() only works with find() and thus is not helpful with aggregate queries
                                  – Felipe
                                  Feb 13 at 5:01
















                                If you downvote, please add a reason so I have the chance to understand - which might also improve future answers!
                                – mrechtien
                                Apr 25 '17 at 14:12




                                If you downvote, please add a reason so I have the chance to understand - which might also improve future answers!
                                – mrechtien
                                Apr 25 '17 at 14:12




                                1




                                1




                                I'm not sure about the downvote but just an FYI: count() only works with find() and thus is not helpful with aggregate queries
                                – Felipe
                                Feb 13 at 5:01




                                I'm not sure about the downvote but just an FYI: count() only works with find() and thus is not helpful with aggregate queries
                                – Felipe
                                Feb 13 at 5:01











                                0














                                Try as bellow:




                                cursor.count(false, function(err, total){ console.log("total", total) })




                                core.db.users.find(query, {}, {skip:0, limit:1}, function(err, cursor){
                                if(err)
                                return callback(err);

                                cursor.toArray(function(err, items){
                                if(err)
                                return callback(err);

                                cursor.count(false, function(err, total){
                                if(err)
                                return callback(err);

                                console.log("cursor", total)

                                callback(null, {items: items, total:total})
                                })
                                })
                                })





                                share|improve this answer


























                                  0














                                  Try as bellow:




                                  cursor.count(false, function(err, total){ console.log("total", total) })




                                  core.db.users.find(query, {}, {skip:0, limit:1}, function(err, cursor){
                                  if(err)
                                  return callback(err);

                                  cursor.toArray(function(err, items){
                                  if(err)
                                  return callback(err);

                                  cursor.count(false, function(err, total){
                                  if(err)
                                  return callback(err);

                                  console.log("cursor", total)

                                  callback(null, {items: items, total:total})
                                  })
                                  })
                                  })





                                  share|improve this answer
























                                    0












                                    0








                                    0






                                    Try as bellow:




                                    cursor.count(false, function(err, total){ console.log("total", total) })




                                    core.db.users.find(query, {}, {skip:0, limit:1}, function(err, cursor){
                                    if(err)
                                    return callback(err);

                                    cursor.toArray(function(err, items){
                                    if(err)
                                    return callback(err);

                                    cursor.count(false, function(err, total){
                                    if(err)
                                    return callback(err);

                                    console.log("cursor", total)

                                    callback(null, {items: items, total:total})
                                    })
                                    })
                                    })





                                    share|improve this answer












                                    Try as bellow:




                                    cursor.count(false, function(err, total){ console.log("total", total) })




                                    core.db.users.find(query, {}, {skip:0, limit:1}, function(err, cursor){
                                    if(err)
                                    return callback(err);

                                    cursor.toArray(function(err, items){
                                    if(err)
                                    return callback(err);

                                    cursor.count(false, function(err, total){
                                    if(err)
                                    return callback(err);

                                    console.log("cursor", total)

                                    callback(null, {items: items, total:total})
                                    })
                                    })
                                    })






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Oct 28 '17 at 14:26









                                    surinder singh

                                    962810




                                    962810























                                        0














                                        MongoDB allows you to use cursor.count() even when you pass limit() or skip().



                                        Lets say you have a db.collection with 10 items.



                                        You can do:



                                        async function getQuery() {
                                        let query = await db.collection.find({}).skip(5).limit(5); // returns last 5 items in db
                                        let countTotal = await query.count() // returns 10-- will not take `skip` or `limit` into consideration
                                        let countWithConstraints = await query.count(true) // returns 5 -- will take into consideration `skip` and `limit`
                                        return { query, countTotal }
                                        }





                                        share|improve this answer























                                        • how about aggregate ?
                                          – Mahmoud Heretani
                                          Jul 3 at 18:23
















                                        0














                                        MongoDB allows you to use cursor.count() even when you pass limit() or skip().



                                        Lets say you have a db.collection with 10 items.



                                        You can do:



                                        async function getQuery() {
                                        let query = await db.collection.find({}).skip(5).limit(5); // returns last 5 items in db
                                        let countTotal = await query.count() // returns 10-- will not take `skip` or `limit` into consideration
                                        let countWithConstraints = await query.count(true) // returns 5 -- will take into consideration `skip` and `limit`
                                        return { query, countTotal }
                                        }





                                        share|improve this answer























                                        • how about aggregate ?
                                          – Mahmoud Heretani
                                          Jul 3 at 18:23














                                        0












                                        0








                                        0






                                        MongoDB allows you to use cursor.count() even when you pass limit() or skip().



                                        Lets say you have a db.collection with 10 items.



                                        You can do:



                                        async function getQuery() {
                                        let query = await db.collection.find({}).skip(5).limit(5); // returns last 5 items in db
                                        let countTotal = await query.count() // returns 10-- will not take `skip` or `limit` into consideration
                                        let countWithConstraints = await query.count(true) // returns 5 -- will take into consideration `skip` and `limit`
                                        return { query, countTotal }
                                        }





                                        share|improve this answer














                                        MongoDB allows you to use cursor.count() even when you pass limit() or skip().



                                        Lets say you have a db.collection with 10 items.



                                        You can do:



                                        async function getQuery() {
                                        let query = await db.collection.find({}).skip(5).limit(5); // returns last 5 items in db
                                        let countTotal = await query.count() // returns 10-- will not take `skip` or `limit` into consideration
                                        let countWithConstraints = await query.count(true) // returns 5 -- will take into consideration `skip` and `limit`
                                        return { query, countTotal }
                                        }






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jan 31 at 20:22

























                                        answered Jan 30 at 0:45









                                        Daniel Varela

                                        1317




                                        1317












                                        • how about aggregate ?
                                          – Mahmoud Heretani
                                          Jul 3 at 18:23


















                                        • how about aggregate ?
                                          – Mahmoud Heretani
                                          Jul 3 at 18:23
















                                        how about aggregate ?
                                        – Mahmoud Heretani
                                        Jul 3 at 18:23




                                        how about aggregate ?
                                        – Mahmoud Heretani
                                        Jul 3 at 18:23


















                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f21803290%2fget-a-count-of-total-documents-with-mongodb-when-using-limit%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        404 Error Contact Form 7 ajax form submitting

                                        How to know if a Active Directory user can login interactively

                                        Refactoring coordinates for Minecraft Pi buildings written in Python