Combine arrays and group them together to calculate the total count of each unique value in the merged array

I have a dataset similar to the following:

{
        "_id" : ObjectId("5a4c6fb6993a721b3479a27e"),
        "score" : 8.3,
        "page" : "@message",
        "lastmodified" : ISODate("2018-01-03T06:49:19.232Z"),
        "createdate" : ISODate("2018-01-03T05:52:54.446Z"),
        "slug" : [ 
            "@APPLE"
        ],
        "__v" : 0
    },
    {
        "_id" : ObjectId("5a4c6fb6993a721b3479a27e"),
        "score" : 9.3,
        "page" : "@BANANA",
        "lastmodified" : ISODate("2018-01-03T06:49:19.232Z"),
        "createdate" : ISODate("2018-01-03T05:52:54.446Z"),
        "slug" : [ 
            "@APPLE"
        ],
        "__v" : 0
    }
    { 
        "_id" : ObjectId("5a4c6fb6993a721b3479a27e"),
        "score" : 5.3,
        "page" : "@BANANA",
        "lastmodified" : ISODate("2018-01-03T06:49:19.232Z"),
        "createdate" : ISODate("2018-01-03T05:52:54.446Z"),
        "slug" : [ 
            "@BANANA"
        ],
        "__v" : 0
    }

My objective is to compute the total sum of scores based on specified filters, like so:

@APPLE: 8.3+9.3 = 17.6 for @APPLE : 17.6,
@BANANA: 9.3+5.3 = 14.6 for @BANANA: 14.6

To achieve this, I need to extract data from the past hour instead of scanning through the entire database. The query for this purpose looks like:

var newTime = new Date();
newTime.setHours( newTime.getHours() - 1 );
db.Test.find({"lastmodified":{$gt: newTime}})

Thus, with this query, I can access only the data from the last hour. However, I am facing confusion regarding how to calculate the sum with these specific filters applied. My attempt at filtering using the following query has not returned any results:

db.Test.find({"lastmodified": {$gt: newTime}}, {$or: [{slug: {$in: ['@APPLE']}}, {page: '@APPLE'}]})

If anyone could offer assistance on this issue, it would be greatly appreciated.

Answer №1

You should attempt this combined query...

db.results.aggregate([
    {
        "$unwind": "$category"
    },
    {
        "$group": {
            "_id": "$category",
            "overallPoints": {
                "$sum": "$points"
            }
        }
    }
]);

Outcome:

{ 
    "_id" : "@ORANGE", 
    "overallPoints" : 9.8
}
{ 
    "_id" : "@PEAR", 
    "overallPoints" : 21.1
}

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

Is there a way to incorporate a background image fadeIn effect for ul using CSS3?

I have a list on my webpage where each item is displayed with a CSS3 rotate animation. After the animation finishes, I want to set a background image with a FadeIn effect. To achieve this, I created a "addbg" class for the ul element like so: ul.addbg{ ...

establishing status within enclosed reaction

In the process of developing a react application, I am encountering difficulties in correctly setting the state with the nested response data received from an api. The state is not aligning as desired. Here is the sample response obtained from the api: [ ...

Issue Arising from Inability to Activate Mongoose Pre/Post Hook During Document Deletion

Struggling with implementing pre and post hooks for document deletion in Mongoose. Tried different methods, from deleteOne to deleteMany, findOneAndDelete, and findOneAndRemove. Also experimented with modifying deleteOne middleware code to first find the d ...

What causes the occurrence of "undefined" after multiple iterations of my code?

I've encountered a curious issue with the code snippet below. Everything seems to be running smoothly except for one thing - after a few iterations, I start getting "undefined" as an output. You can test this for yourself by running the code multiple ...

Dealing with adding up optional values from v-model in Vue.js can be a challenging task

Within this function, I need to display the remaining amount. remainingAmount: function() { return parseFloat(this.sumAmount) - (parseFloat(this.cash) + parseFloat(this.kNet) + parseFloat(this.kNetOnline)); } The three parameters cash ...

Sort through a list of objects by certain properties

I'm currently dealing with two arrays: one contains displayed columns and the other contains objects retrieved from a database, with more attributes than the displayed columns. displayedColumns = ['CompanyName','Ticker', 'Id& ...

Error: The function preciseDiff is not recognized by moment

Encountering an error message: "TypeError: moment.preciseDiff is not a function. I am facing the same issue, wondering if there is a solution or alternative available. I have version 2.24.0 of moment installed. moment-precise-range-plugin In addition, I ...

Arranging pre-selected checkboxes in MUI Datatable

I noticed that the checked data is appearing at the top of MUI data tables without any sorting. Checkbox In this image you can see that all the checked boxes are mixed up without any order. I would like to have all the checked rows displayed together and ...

The issue of receiving undefined in NodeJs while using $not with MongoDB

I'm attempting to create a find command in MongoDB using $not as shown in this link, await Match.find( { type:"Friendly", status:"Pending", "date.fullDate":{$gt: date}, $not:{$or: [{"team1.players":{$elemMatch: {_id:player ...

Access the specific scope I established in Angular console, excluding the entire scope

Is there a way to access only the $scope elements (variables and functions) created in my controller without getting everything ($$childTail, $$childHead, etc)? I know if I use: angular.element(document.querySelector('<selector-name>')).sc ...

The component fails to update even after changes are made to the Redux state

I currently have 4 buttons, each with a different color, and I want to display the last 10 button clicks as colors on 10 squares. The redux state is being used to map and display the square colors, which are also stored in localStorage. When a button is c ...

How to validate using two distinct mongoose instances

As a newcomer to mongoose and nodejs, I am facing an issue with two unique fields in mongoose. How can I properly validate them? Below is the code snippet: model var userSchema = new Schema({ local:{ email:{type:String,required:true,unique:tr ...

Invert the motion within a photo carousel

Is there anyone who can assist me with creating a unique photo slider using HTML, CSS, and JS? Currently, it includes various elements such as navigation arrows, dots, and an autoplay function. The timer is reset whenever the arrows or dots are clicked. Ev ...

From javascript to utilizing ajax calls to interact with php scripts,

I am currently working on a page called edit.php where I need to pass a JavaScript variable to a modal window containing PHP in order to execute a query and retrieve data. Unfortunately, my experience with Ajax is limited and I haven't been able to fi ...

The Angular filter is waiting for the ng-repeat to be populated

I have a filtering system that includes dropdown options to filter the displayed content. The content is fetched from a database and takes a few milliseconds to display. During this time, I encounter several errors related to the filtering system. Does any ...

Is there a way to trigger a Modal to open upon clicking a custom-designed button in MaterialUI?

In my React and Material-UI project, I am attempting to trigger a Modal to open using a custom button. The button also performs other functions, which is why it's important for me to combine the "Modal Opening" action with these additional functionali ...

How can you ensure that the Data Point Values are always displayed when using arrayToDataTable in the Google Charts API?

Just wanted to clarify that even though there is a similar question titled: Google Charts API: Always show the Data Point Values in Graph ...on this website, I am facing difficulties implementing its solution because my chart is using arrayToDataTable. ...

Issue arises when trying to utilize Ajax on the Fancy Box overlay button click and the functionality does not perform as

Hey there! I've got a bit of a silly question for you. So, I'm pretty new to Ajax and fancy box. I've been using fancy box on one of my pages, and it's been working well so far. The issue I ran into was when I tried to make an ajax call ...

Using jQuery's .load() method to load a PHP file can result in an exponential increase in XHR finished loading time with each subsequent load

There seems to be an issue with my code using .load() to load a PHP page into a div whenever the navbar or link is clicked. After multiple clicks, I noticed that the "XHR finished loading" increases exponentially and it appears that the same PHP file is be ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...