Data Filling and Consolidating in MongoDB

Recently, I inquired about a similar issue here: Mongoose/Mongodb Aggregate - group and average multiple fields

I am attempting to utilize Model.aggregate() to determine the average rating of all posts based on date and then further categorized by specific author attributes such as country name or gender. However, I am encountering difficulties in achieving this. I understand that for the initial stage, I need to use $match for filtering by date, and I believe I should employ $lookup to "populate" the author field, though the implementation is not clear to me.

The following code effectively computes the average rating for all posts based on date:

  Post.aggregate([
    { $group: { _id: "$date", avgRating: { $avg: '$rating' }}}
  ]).
  then(function (res) {
    console.log(res); 
  })

Although this is essentially what I aim to do, it does not yield the desired results:

Post.aggregate([
    {$match: {"date": today}},
    {$group: {_id: {"country": "$author.country.name"}, avgRating: {$avg: "$rating"}}}
]).then(function(res) {
    console.log(res)
})

User model details:

const userSchema = new Schema({
email: {
    type: String,
    required: true,
    unique: true
},
birthday: {
    type: Date,
    required: true,
},
gender:{
    type: String,
    required: true
},
country:{
    name: {
        type: String,
        required: true
    },
    flag: {
        type: String,
        // default: "/images/flags/US.png"
    }
},
avatar: AvatarSchema,
displayName: String,
bio: String,
coverColor: {
    type: String,
    default: "#343a40"
},
posts: [ 
    {
    type: Schema.Types.ObjectId,
    ref: "Post" 
    }
],
comments: [
    {
        type: Schema.Types.ObjectId,
        ref: "Comment"
    }
],
postedToday: {
    type: Boolean,
    default: false
},
todaysPost: {
    type: String
}
}) 

Answer №1

Once you have retrieved data from MongoDB, you can populate an aggregation. The query will resemble the following:

modelName.aggregate([{
                                $unwind: ''//if Necessary
                            }, {
                                $group: {
                                    _id: {"country":"$author.country.name"},
                                    avgRating: {
                                        $avg: '$rating'
                                    }
                            }])
        .exec(function(err, results) {
            // ERROR HANDLING
            // Callbacks                
            modelName.populate(columnName, {path: '_id'}, function(err, populatedResult) {
                // Populated columnName within TaleName
            });
        });

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

Guide on transferring Context to the loader in React-Router-6

In my development setup, I am utilizing Context for managing the global loading state and React-router-6 for routing. My approach involves incorporating loader functionality in order to handle API requests for page loading. However, a challenge arises when ...

Handling Forms with Node and Express

I'm currently following a guide to create a node/express application using the jade template engine. I've encountered a 404 error when trying to submit a form. In my routing, I have this line: app.post('sign_up', sign_up); which is caus ...

Three.js: Spherical boundary of an object that has been resized

When working with a collection of 3D shapes such as pyramids, cubes, octahedrons, and prisms, I encountered an issue with building described spheres around them. While it's straightforward to create the spheres using geometry.boundingSphere due to its ...

The process of obtaining HTML input using JavaScript

I have included the following code snippet in my HTML form: <input type="text" name="cars[]" required>' It is worth noting that I am utilizing "cars[]" as the name attribute. This allows me to incorporate multiple ...

Invoking Javascript Functions using their names

Suppose I have the following element on my page... <span data-function="DoSomething">Click</span> ... and then add the following to my page header... $(document).ready(function() { $('[data-function]').each(function() { ...

Can the table be automatically updated on page reload?

My goal is to populate a table using $.ajax(), but the content is not showing up when the page first loads. Is there something missing in my implementation of the $.ajax() function? Here's the HTML structure: <div class="row"> <div clas ...

Tips for customizing the appearance of the day button in a React Material-UI date picker

In my React project, I am using material-ui date picker and I am looking for a way to customize the styling of the day buttons. Specifically, I want to change the text color of the available days. By default, as seen in the screenshot, the text color is bl ...

Invoke a different route within Express Router when it needs to display a Not Found error (404)

Hey there, how are you? Below is the code I've been working on: const router = Router(); router.use( `${routePrefix}/v1/associate-auth/`, associateAuthRoutesV1(router) ); router.use( `${routePrefix}/v1/associate/`, JWTVerify, ...

Tips for adding a CSS marker to the Videogular timeline at a designated time

My HTML player application allows users to search for a term and then displays the results along with the time when those words appear. By clicking on a specific sentence, the HTML player will start playing from that location. However, I would like to enha ...

Setting the height of a div tag in CSS/HTML5 to match the current height of the browser window

Is there a way to make the height of my div tag always equal to the height of the browser's window, so it adjusts automatically when the browser is resized? I have tried using .class { height: 100%; } But this doesn't work. I've learne ...

Maintaining hover effects even when elements are not in view

I am facing an issue with my absolutely positioned <div> (which serves as a menu) located in the corner of a webpage. The problem arises when I try to animate it on hover, but as soon as the cursor moves beyond the viewport, the hover action stops. I ...

Different methods for dynamically altering the style attribute

Here's some code I wrote: <html> <head> <style> .containerTitle { background-color:silver; text-align:center; font-family:'Segoe UI'; font-size:18px; font-weight:bold; height:30px; } ...

Tips for maintaining the selected radio button state after refreshing the JSP page: Ensuring that the radio button remains selected

I need help with refreshing a page after clicking on one of two radio buttons. I've tried multiple solutions but haven't been successful so far. Can someone assist me? <script> $(document).ready(function() { $(document).on('c ...

Changing the size of icons in an Alert using Material UI with React

Recently, Material UI unveiled the new 'Alert' component. Everything seems to be working well, except for the fact that I can't find a way to adjust the size of the icon. Here is my code snippet: <Snackbar open={true}> <Alert ...

"An issue with AngularJS ngTable causing a delay in the rendering of Ajax

Struggling with ngTable Setup Having trouble mastering the use of ngTable by going through the ngTable ajax demo. I attempted to follow along with the example as closely as possible, but I'm encountering a deviation in defining an ngResource inline w ...

Customizing content based on Route - Utilizing Node.js/React

I am currently working on setting up routes for different pages of store profiles in my Node app. I have been doing some research online and have come to understand how to adjust the parameters, but I am struggling with figuring out how to dynamically chan ...

Initiate an AJAX request to the server upon beforeunload event

It seems that starting with Firefox version 4, binding the window jQuery object to beforeunload is no longer effective. I want to send an AJAX post request to delete data from my server's memcache. When I refresh the only open tab, I can observe tha ...

Guide on inserting the exact date from a String into MongoDB using Java

I have a CSV text file containing data retrieved from MySQL including a field called DateOfTransaction with values like "21/08/2012". I developed a Java program to read and insert this data into MongoDB. Here's the code snippet for inserting the date: ...

Typescript interface design for nested objects in a hierarchical structure

When data is received from the server in JSON format, it typically looks like the example below (details have been modified): { "apple": { "fruitName": "apple", "types": { "greenApple": { ...

Mobile devices do not support HTML5 Video playback

Here is the HTML5 Video code I am using: <div id="lightBox1" class="lightBox"> <video id="video" controls preload="metadata"> <source width="100%" height="470" src="/ImageworkzAsia/video/iworkzvid.mp4" type="video/mp4"> ...