Determining the total number of documents through aggregation while implementing skip and limit functionality

Is there a way to retrieve the total count of documents when implementing aggregation along with limit and skip in a query similar to the one below?

  db.Vote.aggregate({
       $match: {
           tid: "e6d38e1ecd",
           "comment.topic": {$exists: 1},
       }
   },{
       $group: {
           _id: {
               topic: "$comment.topic",
               text_sentiment: "$comment.text_sentiment"
               
           },
           total: {$sum: 1},
           
       }
   },{
       $project: {
           topic: {
               name: "$_id.topic",
               occurence: "$total"
           },
           sentiment: "$_id.text_sentiment"
       }
   },{
       $sort: {"topic.occurence": -1}
   })
    .skip(SKIP)
    .limit(LIMIT)

While the above query enables me to retrieve documents within the specified LIMIT, I am also interested in knowing the total count of documents each time I execute the query. How can I achieve this?

UPDATE Although some have suggested utilizing $facet, I'm uncertain about its implementation. For instance, if the aggregation fetches 50 documents unlimitedly, how can I incorporate $facet to not only retrieve LIMIT documents but also the metadata containing the total document count?

Referencing a functional query on MongoDB Playground that I crafted, how can I leverage $facet or any other approach to obtain the total count?

Answer №1

To tackle this issue, one approach is to utilize the $facet feature. However, a drawback of this method is that it combines all your documents into a single document:

db.Vote.aggregate(
  {$match: {tid: "e6d38e1ecd",  "comment.topic": {$exists: 1}}},
  {$group: {_id: {topic: "$comment.topic", text_sentiment: "$comment.text_sentiment"},
           total: {$sum: 1}}
   },
  {$project: {topic: {name: "$_id.topic",  occurence: "$total"},
           sentiment: "$_id.text_sentiment"}
  },
  {$facet: {
    data: [{$sort: {"topic.occurence": -1}}, {$skip: SKIP}, {$limit: LIMIT}],
    total: [{ $count: "total" }]
  }}
)

Another alternative is to employ $setWindowFields to append the total count to each individual document, thus maintaining them as distinct entities:

db.Vote.aggregate(
  {$match: {tid: "e6d38e1ecd",  "comment.topic": {$exists: 1}}},
  {$group: {_id: {topic: "$comment.topic", text_sentiment: "$comment.text_sentiment"},
           total: {$sum: 1}}
   },
  {$project: {topic: {name: "$_id.topic",  occurence: "$total"},
           sentiment: "$_id.text_sentiment"}
  },
  {
    $setWindowFields: {output: {totalCount: {$count: {}}}}
  })
    .skip(SKIP)
    .limit(LIMIT)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on preserving a dynamic web page within a Cordova application

I have developed a project and To Do list App that operates on a single HTML page with just an "add To Do list" button. Users can click on this button to create a To Do list and add tasks within it, all of which are dynamically generated as HTML elements. ...

Combining Django's CSRF token with AngularJS

I currently have Django running on an Apache server with mod_wsgi, and an AngularJS app being served directly by Apache rather than through Django. My goal is to make POST calls to the Django server that is utilizing rest_framework, but I am encountering d ...

Find the mean of three numbers stored in an array of objects

I am currently working on a school assignment that requires me to develop a function for calculating the average mark of 3 students using an existing object in an array. Below, you can see the array and function that I have been working on as part of this ...

display in a modal-body and jdata

Within my MySQL database, there are several columns stored, including: headline, description, place, resume Currently, I am able to display the headline and description in a modalbox using the following code. However, I now wish to also showcase the pl ...

Is it possible to load asynchronous JS and then execute functions?

Is there a way to make my script behave like the Google Analytics JavaScript snippet? Here is an example of what I have: (function(d, t) { var g = d.createElement(t), s = d.getElementsByTagName(t)[0]; g.src = 'myjs.js'; s.par ...

Selenium error: Element is unclickable ... Another element is blocking the click, but go ahead and click

When attempting to utilize the code snippet below return this.driver.findElement(By.css("div[class*='img']")).click(); An error occurs: Uncaught WebDriverError: unknown error: Element is not clickable at point (525, 889). Other element would r ...

Enhancing jQuery Mobile listview with voting buttons on each item row

I am looking to incorporate 2 vote buttons within a jQuery mobile listview, positioned on the left-hand side and centered within each list item. While I have managed to achieve this using javascript, my goal is to accomplish it without any additional scrip ...

What could be causing my ES6 code to fail compilation post npm install?

Check out my npm module built with es6 on Github here. Within the package.json file, there are scripts designed to ensure proper building of the es6 modules. When using npm publish and npm install within the module's directory, everything works fine. ...

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

Exploring the world of color in Google visualization charts

I am currently working on a project that requires me to add different colors to specific zones on a graph. I am looking to use colors such as blue, red, yellow, and green. Here is the outcome I have achieved: https://i.sstatic.net/0AdC7.jpg I am aiming f ...

Can I extract JSON data from the AJAX response?

When receiving JSON data, such as in the example below, it is often necessary to separate each value into individual variables: var reviewDate ='2015-06-01T05:00:00Z' var developers ='Ankur Shah,Srikanth Vadlakonda,Tony Liu, Qiuming Jie&ap ...

Executing form validation upon submission of a form from the view in BackboneJS

Recently, I delved into using Backbone.js to organize my JavaScript code and create modular applications. However, I encountered a snag when dealing with events. My goal is to develop a simple View that can handle forms and validate them. Eventually, I pl ...

Having trouble retrieving textfield value with jQuery

On my website, I have an invoice.jsp page that requires jQuery to calculate values in textboxes. Within the invoice, there is a quantity textbox. When a user enters a quantity, the price should be dynamically calculated as (total_subPrice= unit_price * qu ...

Configuring route for serving static files in an Express server

I'm completely new to working with express, but I am eager to learn and follow the best practices. My goal is to serve files like CSS or index.html from a folder called 'public'. I have seen examples using .use and .get methods as shown belo ...

What techniques can be applied to utilize JSON data in order to dynamically create menu components using the map method?

My current challenge involves dynamically generating a set of menu items using data retrieved from a JSON file. I've attempted to achieve this by mapping the values with props, but it seems like I'm overlooking something. Below is the code snipp ...

Use the Nodejs HTTP.get() function to include a custom user agent

I am currently developing an API that involves making GET requests to the musicBrainz API using node.js and express. Unfortunately, my requests are being denied due to the absence of a User-Agent header, as stated in their guidelines: This is the code sn ...

Tips for changing an input value when clicked using JQuery

Struggling to create an interactive mind mapping tool using JQuery? One challenge I'm facing is editing the content of a div once it's been set. I've implemented a function that successfully adds text to a div within the (mind-container). H ...

generating a new item using Mongoose searches

How can I generate an object based on queries' results? The table in the meals operates using database queries. How do I handle this if the queries are asynchronous? const getQueryResult = () => { Dinner1300.count().exec(function (err, count) ...

What is the method to dynamically modify the value of location.href using vanilla javascript?

I have a button that looks like this: <button type="button" class="play-now-button" onclick="location.href='www.yahoo.com'">Play Now</button> However, I want to change the location.href value using vanilla JavaScript. The code below ...

Show the present category name within breadcrumbs (utilizing angularJS)

Struggling to display category and vendor names on breadcrumbs? Utilizing the ng-breadcrumbs module but encountering difficulties in making curCategory and curVendor globally accessible. Tried various methods without success. Below is the HTML code snippe ...