Discovering the variance in count values between two queries in MongoDB

    
Query Case 1: db.TestItems.find({
    $and: [{
    $or: [
    {"data.questions.stimulus" : /\\\\\w+/},
    {"data.questions.options.label" : /\\\\\w+/},
    {"data.questions.validation.validResponse.value" : /\\\\\w+/},
    {"data.questions.validation.altResponses.value": /\\\\\w+/},
    {"data.questions.hints.label": /\\\\\w+/}`enter code here`
    ]}, {"createdBy._id": ObjectId("5e9dac4699a7bb0007e33460")}]
    }).count();

    Query Case 2: db.TestItems.find({"createdBy._id": ObjectId("5e9dac4699a7bb0007e33460")}).count();

I'm eager to determine the distinction between Query Case 2 and Query Case 1?

Answer №1

To enhance your query performance, you can utilize aggregation with $facet to execute both queries simultaneously followed by a calculation using $subtract. Here's an example:

db.collection.aggregate([
   {$facet:{
             total:[
                    {$match: {"createdBy._id": ObjectId("5e9dac4699a7bb0007e33460")}},
                    {$count: "count"}
             ],
             constrained:[
                    {$match:{
                       "createdBy._id": ObjectId("5e9dac4699a7bb0007e33460"),
                       $or:[
                            {"data.questions.stimulus" : /\\\\\w+/},
                            {"data.questions.options.label" : /\\\\\w+/},
                            {"data.questions.validation.validResponse.value" : /\\\\\w+/},
                            {"data.questions.validation.altResponses.value": /\\\\\w+/},
                            {"data.questions.hints.label": /\\\\\w+/}
                       ]
                    }},
                    {$count: "count"}
             ]
   }},
   {$addFields: {
                 total:{$arrayElemAt:["$total",0]},
                 constrained:{$arrayElemAt:["$constrained",0]}
   }},
   {$addFields:{
       difference:{
           $subtract:[
                      "$total.count",
                      "$constrained.count"
                     ]
       }
   }}
])

An alternative approach would be to leverage $group as shown below:

db.collection.aggregate([
    {$match: {"createdBy._id": ObjectId("5e9dac4699a7bb0007e33460")}},
    {$group: {
       _id:"$createdBy._id",
       total:{$sum:1},
       constrained:{
          $sum:{
            $cond:{
                 if:{
                     $or:[
                          {$regexMatch:{
                                        input:"$data.questions.stimulus", 
                                        regex: /\\\\\w+/}},
                          {$regexMatch:{
                                        input:"$data.questions.options.label", 
                                        regex: /\\\\\w+/}},
                          {$regexMatch:{
                                        input:"$data.questions.validation.validResponse.value",
                                        regex:/\\\\\w+/}},
                          {$regexMatch:{
                                        input:"$data.questions.validation.altResponses.value",
                                        regex: /\\\\\w+/}},
                          {$regexMatch:{
                                        input:"$data.questions.hints.label",
                                        regex: /\\\\\w+/}}
                     ]
                 },
                 then:1,
                 else:0
            }
          }
        }
    }},
    {$addFields:{difference:{$subtract:["$total","$constrained"]}}}
])

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

The ASP.NET controller is unable to process a null array

I am developing an application using Angular.js and ASP.NET. Here is the model I have defined: public class Dealer : EntityBase { ... public virtual List<DealerDefinedService> DealerDefinedServices { get; set; } public virtual List<De ...

Extracting information and converting it into JSON format using Express

I am currently extracting data from a website and attempting to display it in the browser as JSON. However, although I can see the data when using console.log() on the recipes array, nothing is being sent to the browser. Why is the JSON array not showing ...

Spotlight the flaw in the card's backbone using JS

What's the most effective method for emphasizing an error card view in backbone? Initially, I render 10 cards as UI where users input details in each card. Upon clicking submit, I validate all the details by parsing through collection->models. Curr ...

The console logs indicate true, yet contradicts with a false assertion in the if statement

I am facing an issue with this code router.get("/timecard", ensureAuthenticated, async(req, res)=>{ users = await User.find(); console.log(req.user.cwlEmployee); if(req.user.cwlEmployee !== true){ req.flash('error_msg', &a ...

Troubleshooting issue: Utilizing $(this) with Vue.js in jQuery method is not functioning as

Initially, I understand that combining jQuery with Vue is not advisable. Nevertheless, I am attempting to modify an element after a click event but encountering issues with $(this). methods: { openSMS() { $(this).hide(); // <-- facing difficulty ...

Using ternary operators and filters in a binding with AngularJS

I currently have a basic data binding setup: {{ myAccount.Balance }} Then I decided to incorporate a couple of filters: {{ myAccount.Balance | filter1 | filter2 }} Nevertheless, I am interested in using a ternary operator for scenarios where the Balanc ...

What is the method to obtain the selector string for an HTML node element?

Essentially, my goal is to extract the selector string from an HTML element. Specifically, I want to start with the HTML element and retrieve its selector string (for example: button#myButton) function onclicked(e){ console.log(e.target); // This returns ...

What is the best way to execute a command in a running NodeJS project directly from the command line?

In my server project, I have implemented a feature that checks its settings file every 5 minutes for any changes and updates variables accordingly. However, I am also looking into the option of triggering this function from the command line so that I can ...

What could be causing bundle.js to remain in a pending status on my website?

Whenever I try to open a page from my project, the browser keeps showing loading forever and in the network tab, the status of bundle.js is pending. (Interestingly, if I open other routes of the project, everything works fine). If I remove all product var ...

Using multiple filters to narrow down search results in Mongoid

Currently, I have specific filter conditions that need to be applied to the Item model. condition1_ids = get_condition1_ids # array containing ids condition2_ids = get_condition2_ids # array containing ids condition3_ids = get_condition3_ids # ...

How to set default props in Vue Select component?

I have been utilizing the vue-multiselect plugin from this website: Given that I plan to use it frequently, I am interested in establishing some default props. For instance, my aim is to have the selectLabel prop set as an empty string and possibly con ...

"Utilizing Angular's $http.post to extract data from resolved promises

Can you help me figure out how to successfully send data through $http.post that I receive from a function using $q.defer()? Here is the code snippet: HTML <input type='text' ng-model='name'/> <input type='file' id= ...

Tips on storing JSON array data in mongoose via req.body?

I've been struggling with this issue for some time now. After successfully using JSON and req.body to save data to my MongoDB database in Postman, I decided to work with arrays for the first time. However, I'm encountering difficulties. (Just t ...

Is the removal of the Vue-Router link happening when you click on the top app bar icon in Google Material

Review of the following code snippet: <!DOCTYPE html> <html> <head> <title>test</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='vie ...

Using jQuery AJAX in combination with PHP to store data in a MYSQL database

I am in search of a jQuery AJAX script paired with a PHP script that can store information when a button is clicked. The jQuery function should have three predefined variables, set before the method call. Although I have completed the basic functionality, ...

Attempting to decode JSON data

I'm new to node.js and trying to learn how to send a JSON object using REST. However, I keep getting an error message that says "SyntaxError: Unexpected token  in JSON at position 0". I've checked the JSON using an online validator and it seem ...

When navigating to '/blogs/', the index.js file in Next.js will automatically open

I'm working on a project using next.js and I want to ensure that when I visit 'localhost:3000/blogs/', it opens the index.js page. The index.js file is located in the 'blogs' folder of my project. Currently, it does open properly ...

When you click on a sublevel in the vertical CSS and JavaScript onclick menu, it disappears automatically

I'm a beginner when it comes to Javascript, and I'm still getting the hang of CSS/HTML. Currently, I am working on creating a vertical menu using CSS and javascript. My goal is to have the sublevels appear on the right side of the menu when someo ...

Why is the MEAN stack DELETE function failing to work properly? Could the issue be related to

My Angular4, Express 4.15 and Node 7.9 setup is working well with GET, POST, PUT requests. However, I'm facing an issue with the delete function. I am using Mlab for my MongoDB and connecting through mongojs. Edit - When sending a DELETE request via ...

What is the process for determining the primary shard in a MongoDB cluster?

I currently have set up 3 mongod, 2 mongos, and a single config server. When I check sh.printShardingStatus(), it indicates one node as the primary. How does MongoDB determine which shard is the primary for un-sharded collections and is it possible to ch ...