Retrieve the total count of shops from the previous 12 months within a MongoDB database

I am looking to track the cumulative number of shops over the past 12 months.

Sample Collection
{
  _id: '5f3d4e5e01e06f0007335233',
  name: 'Walmart',
  createdAt: '2020-08-22T17:42:09.908+00:00'
}

Currently, I am able to retrieve the results for new shops opened in the past 12 months.

Shop.aggregate([{
  $match: {
     createdAt: {
      $gte: {
        $date: {{moment.utc().subtract(12, "months").startOf('day').toISOString()}}
      },
      $lt: {
        $date: {{moment.utc().startOf('day').toISOString()}}
      }
    },
    }
}, {
  $project: {
    dateParts: {
      $dateToParts: { date: '$createdAt' }
    },
    total: true,
  }
}, {
    $group: {
      _id:  {
        month: '$dateParts.month',
        year: '$dateParts.year',
      },
      numShops: { $sum: 1 },
    }
}])

The above query provides the number of new shops for the past 12 months. However, I need a query that gives me the total number of shops up until a specific month.

The expected result from the query should look something like this:

[{
  date: 'Aug-2020',
  numShops: 100,   // Total number of shops until Aug-2020
}, {
  date: 'Sep-2020'
  numShops: 230, // Total number of shops until Sep-2020
}, ....
]

Answer №1

When it comes to retrieving the month as a string in MongoDB, the most efficient approach is to handle it client-side after querying.

There are different ways you can achieve this within the query itself:

  • $group: Perform the operation correctly
  • $arrayElemAt: Select a specific month string from the provided months array
  • $toString: Convert the number for year into a string
  • $concat: Prepare the date string
let months = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
db.collection.aggregate([
  {
    $group: {
      _id: {
        year: { $year: "$createdAt" },
        month: { $month: "$createdAt" }
      },
      numShops: { $sum: 1 }
    }
  },
  {
    $project: {
      _id: 0,
      numShops: 1,
      date: {
        $concat: [
          { $arrayElemAt: [months, "$_id.month"] },
          "-",
          { $toString: "$_id.year" }
        ]
      }
    }
  }
])

Try it out on Playground

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 create an update function that allows an edit form to replace existing text with new content?

I'm struggling with creating a straightforward update function to edit an ingredient and save the changes. Despite my efforts, I can't seem to get it right. Every time I submit the form, I just end up with the same unchanged ingredient. Here is t ...

Creating a Choropleth map using React: A step-by-step guide

Currently, I am attempting to develop a Choropleth map of Spain in React using Leaflet. Below is the code I have written: import React, { useEffect, useRef, useState } from 'react'; import { MapContainer, TileLayer, GeoJSON, FeatureGroup } from & ...

Is there an issue with multiple parameters in the query string causing an error

My router is designed to work when two specific query parameters are inserted. For example, the URL http://localhost:3000/country/?category=phone&subcategory=oppo works perfectly fine. However, if only one parameter is provided like in this URL - http: ...

Removing a value from an array of objects in Angular 2

There is a single array that holds objects: one = [ {name: 'Name', key: '4868466'}, {name: 'Name', key: '4868466'}, {name: 'Name', key: '4868466'}, {name: 'Name', key: & ...

Error: The checkbox was clicked, but an undefined property (includes) cannot be read

Link to live project preview on CodeSandbox Visit the product page with checkbox I have developed a code snippet that allows users to filter products by checking a box labeled "Show Consignment Products Only", displaying only those products with the term ...

Issue with MongoDB concurrent insertion while stress testing

During my load tests, I often come across a scenario where the following code snippet causes an error: var person = Persons.findOne(); if(person == null){ Persons.insert(newDocument); } The error occurs because the insert operation conflicts wit ...

Angular 2 - The creation of cyclic dependencies is not allowed

Utilizing a custom XHRBackend class to globally capture 401 errors, I have encountered a dependency chain issue in my code. The hierarchy is as follows: Http -> customXHRBackend -> AuthService -> Http. How can this problem be resolved? export cla ...

Importing variable from a JavaScript file in Angular 6

I am currently working on a project using Angular 6 where I need to include styles from an external js file in order to create a customized Google Map. However, I'm facing issues with importing this file into my .ts code. Any suggestions or guidance w ...

Delete a specific row from a table in one parent container based on the content of another parent

Before accusing this of being a duplicate, please read carefully. I have a unique table structure that appears as follows: <td> <table class="schedule_day_table"> <tr> &l ...

cannot update array inside a document using mongo forEach

My task involves creating a mongo script to be executed in RoboMongo, which will iterate through all documents within a collection. Each document includes an array called myArray. The structure of the documents is as follows: { "name": "myApp", "myArr ...

What could be causing the misalignment of my request and response messages?

Currently, I am going through a Node.JS basics book and have successfully created two programs - one responder and one requester. The responder: "use strict"; const fs = require("fs"); const zmq = require("zmq"); const responder = zmq.socket("rep"); // ...

Utilizing the OrientDB HTTP API within an Angular platform - a comprehensive guide

When trying to query OrientDB from an Angular service method, authentication-related errors are encountered. It appears that two GET requests are required for successful querying of OrientDB. An Authentication call: Requesting http://localhost:2480/conne ...

Error: The OrbitControls function is not recognized in THREE.JS

const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); const controls = new OrbitControls(camera); camera.position.set(200, 0, 0); controls.update(); const geometry = new THREE.S ...

What is the syntax for accessing an element within an array in a function?

This code snippet retrieves an array of users stored in a Firestore database. Each document in the collection corresponds to a user and has a unique ID. const [user] = useAuthState(auth); const [userData, setUserData] = useState([]); const usersColl ...

The touch events are not detected on Pixi.js when buttons are placed on a stage that has been both scaled and

Currently, I am developing a game using pixi js. In order to ensure that the game appears consistent on all screens, I have implemented the following scaling logic: this.scale = Math.max(this.viewWidth, this.viewHeight) / (2048 * this.ratio); Additionall ...

Modify a number with a check box using inline Ajax

I have an HTML structure similar to this example: <li><label class="desc"><font color="green">Want to receive emails ($<span id="price">50</span>/month)</font></label> <input type="checkbox" checked ...

Tips for generating a <span> element using the img alt tag and inserting it following the <img> element

I have a set of images with 'alt' tags and I would like to extract the 'alt' tag for each img and create a <span> + alt tag + </span> line after each image. I am unsure of how to achieve this using jQuery. The desired outpu ...

How can I modify an array in Couchbase by using an N1QL query?

{ "name":"sara", "emailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcde8e2ea9627225c4b9a3afa7bbcc808cb554a1adaf">[email protected]</a>", "subjects" : [{ "name":"Math", "tutor":"alice", "classes" ...

Upon clicking the button, the system triggers an update to the database

I am currently working on an interface that involves buttons for updating a database. For example, I have a variable named "Estado" which is initially set as "emAvaliacao". When the button "Aceite" is clicked, the value of "Estado" changes to "Aceite". Th ...

The state of my React components keeps disappearing

Within my code, I have implemented a click event on the InterestBox to trigger updates in its appearance and alter the state of its parent container. However, despite inspecting the element using React Developer Tools and attempting API requests, the stat ...