Determine the quantity of size objects in a MongoDB project that meet a specific condition

Hello, I am working with a posts collection in mongodb that has an authors field. When I execute the following command:

db.posts.aggregate( [ {$project:{ size: {$size: {$ifNull:["$authors", []] }}}} ] )

The result I get looks like this:

{ "_id" : ObjectId("58c917fe48ad625ee8f49714"), "size" : 30 }
{ "_id" : ObjectId("58c91b83895efc5f0f67ba1a"), "size" : 0 }
{ "_id" : ObjectId("58c91cfd2971c05f310fccb8"), "size" : 30 }
{ "_id" : ObjectId("58c91eb7a826965f85571656"), "size" : 30 }
{ "_id" : ObjectId("58c921a1cb2bc85fa77e593a"), "size" : 30 }

My goal is to count how many times the size is not equal to 0. In this case, the desired result would be 4.

I attempted to achieve this using the query "db.posts.aggregate( [ {$project:{ size: {$size: {$not:{"$authors": 0} }}}} ] )" without any luck...

Answer №1

In order to retrieve a count of documents using the $match and $count aggregation methods, you can use code similar to the example below. For more information, refer to MongoDB Aggregate $count

 db.articles.aggregate( 
   [ {
     $match:{ status: 'active' }
   }, {
    $count:'total'
   } ] )

The result should appear as follows:

 { "total" : 7 }

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

What is the best way to utilize JSON.stringify for substituting all keys and values?

In my current project, I am exploring how to leverage the replacer function argument within JSON.Stringify in JavaScript to alter the word case (toUpper / toLower case). The challenge I am facing is that my JSON data is not simply key:value pairs; some val ...

The onCall function in Firebase's realtime database does not provide a response data object when executing the remove() operation

When using onCall to perform a remove operation from a realtime database, I encountered an issue where the response only returned null instead of the expected data object. Strangely, I have used onCall for other operations like update and always received a ...

Consistent manipulation of the DOM through the Drag/Touchmove event

Seeking to incorporate Mobile Components through native Javascript and AngularJS. During my work on developing a Pull To Refresh directive for AngularJS, I utilized the touchmove event on a UL list. The goal was to pull a concealed div over a list with cu ...

Tips for saving and editing a file with JavaScript

I need a website visitor to input text into a text area on my site. When they submit the form, I want the entered text to be saved in a .txt file located in the same directory as the current web page. I am unsure of how this can be accomplished, and if i ...

I seem to be stuck in an endless loop within React and can't find a way to break free

Currently, I am utilizing the useState() function along with an array errors[] as part of the state and a function setError() to pass the useState() function to child elements for calling purposes: const [errors, setErrors] = useState([]); //-------------- ...

I attempted to use the Stripe API, but it seems to be non

I seem to be encountering an issue with the stripe.customers.create. My goal is to create a new Stripe customer using the email address of the current user, and then update my user with the generated customer.id. Despite the fact that stripe.customers.cre ...

Scripting for MongoDB to import numerous JSON files in a batch process

Struggling to import a series of JSON files into MongoDB using a script, here is the code I am trying to use: for i in /home/betafish/Desktop/clsnr/*.json; do mongoimport --dbpath /home/betafish/Desktop/mongodb/data/db clsnr --collection ${i/.json/} -- ...

JavaScript Failing to Validate User Input in Form

I'm a beginner in JavaScript and I'm trying to validate a simple date of birth input, but for some reason, it seems that the JavaScript file is not working. No matter what I input, it always goes through, so I'm trying to figure out what&apo ...

What is the best way to retrieve id elements from a hidden field in jquery?

I'm working with a form that contains hidden fields and I need to retrieve the id of each hidden field. My goal is to potentially remove hidden elements using their id using jQuery's Remove methods. Form: <form id="postform" method="post" ac ...

Organize tabs with ease in the bootstrap-tabdrop plugin

My webpage features a navigation bar along with the bootstrap-tabdrop plugin, which places tabs in a dropdown menu if there are too many to display on one line. The main objective is: No action when navigating through currently displayed tabs. Clicking o ...

Traverse through a collection of file paths, import JSON files, and store them in MongoDB using Pymongo

I have a large file folder containing over 1000 JSON metadata files. I've compiled a list of the file paths and now I'm attempting to: read each JSON file from its file path extract only the key value pairs that interest me store them in a vari ...

Utilizing Java Nashorn with WebEngine events

I'm having trouble processing events from a webEngine in Nashorn. Despite setting up the code to handle the "load" event, nothing is being printed or indicating that any events are triggering from the webEngine. #!/usr/bin/jjs -fx engine = (v=new(s=j ...

Front end Forget Password feature of MERN stack is currently not functioning properly, unlike Postman which is working perfectly

Having trouble with the MERN stack Forget Password feature on the frontend (works fine in Postman). After entering the email and clicking send, an error appears - user not found. I've been attempting to troubleshoot this issue without success. Any adv ...

Different ways to loop through varying grid dimensions

I'm struggling to find a solution to the following problem: I have 5 grids in a row with sizes md={2}, md={3}, md={2}, md={2}, md={3} Now I need to loop through them, but since the grid sizes are different, how can I manage them? <Grid item xs={ ...

Unlocking the potential of nested arrays in MongoDB: a guide to accessing multi-dimensional arrays

Currently, I am dealing with querying the array of array fields in MongoDB. I have managed to access the 'field1.field2', but it only returns the value of field1:{field2:[Array]}. field1:Object field2:[Array] 0:Array 0:Object In ...

The value of the jQuery data on click event handler becomes 'undefined' when used within an AJAX handler

When I click on the Positive or Negative buttons, a jQuery event handler function is triggered. Each button passes different data objects to the handler. However, within the AJAX POST handler, I am unable to access the data from the click event. $('# ...

There seems to be an issue with .ENV functionality in Razzle JS

Attempting to deploy a Razzle project on an Ubuntu server has been challenging. I have created a .env file with two variables: port=80 and host=192.168.1.5. However, when running the project, it defaults to localhost:3000. I've tried exporting PORT=80 ...

The main.js file will be served by nodeJS using express

After developing a nodeJS server using express, I encountered an issue where the server was only delivering the index.html file and not the accompanying main.js file. Both files are located in the same directory. app.get('/', function (req, res) ...

Having trouble retrieving data from the json file

Using Ajax to obtain a JSON update: $(document).ready(function(){ $('form').submit(function(event){ event.preventDefault(); var form = JSON.stringify($('form').serializeArray()); $.ajax ({ u ...

FireFox 3.0.1: Failure to Modify Width and Height Using jQuery

Currently, I am utilizing the jQuery user interface to adjust the size of a DIV element and also resize the embedded YouTube video within it. For more information, you can visit this link. When the main DIV is resized, the YouTube video should automatica ...