"Utilizing MongoDB's aggregate function to filter data by specific

I'm attempting to calculate the average temperature and humidity from my JSON response at 15-minute intervals using the MongoDB Aggregate framework. However, I'm encountering a

SyntaxError: invalid property id @(shell):2:0

This is the code I am using:

var datetime = new Date();
var interValue = 15*1000*60;
datetime.setHours(datetime.getHours() - 1 + interValue);
var endtime = new Date();
db.sensordata.aggregate([
{ $match : { datetime : { $gte : datetime, $lt: endtime } } },
{
        $group: {
            _id: {
                Time: "$datetime",
                Humidity: { "$avg" : "$humidity" },
                Temperature: { "$avg" : "$temperature"}
            },
        },
    },

    { 
        $project :{ _id : 1 , Humidity : 1, Temperature: 1 } },
                            { $limit : 10 },
                { $sort :  {"_id.Time":1, "Humidity":1, "Temperature": 1}}
            ])

Here is my JSON response:

[{ "_id" : ObjectId("585db63541472bf7683eb3c5"), "datetime" : ISODate("2016-12-23T23:41:41.897Z"), "temperature" : 19, "humidity" : 23 }
{ "_id" : ObjectId("585db63a41472bf7683eb3c6"), "datetime" : ISODate("2016-12-23T23:41:46.927Z"), "temperature" : 19, "humidity" : 23 }
{ "_id" : ObjectId("585db63f41472bf7683eb3c7"), "datetime" : ISODate("2016-12-23T23:41:51.956Z"), "temperature" : 19, "humidity" : 23 }
{ "_id" : ObjectId("585db644483ab4f778a635bf"), "datetime" : ISODate("2016-12-23T23:41:56.991Z"), "temperature" : 19, "humidity" : 23 }
{ "_id" : ObjectId("585db64a483ab4f778a635c0"), "datetime" : ISODate("2016-12-23T23:42:02.032Z"), "temperature" : 19, "humidity" : 23 }]

Additionally, I am receiving an empty array.

Thank you :)

Answer №1

The issue lies within the $group pipeline stage.

When grouping, ensure that the field(s) you wish to use for grouping are included only in the _id field.

If you intend to group your data by the date field, consider the following approach:

$group: {
        "_id": {"Date":"$date"},                
        "Sales": { "$sum" : "$sales" },
        "Profit": { "$sum" : "$profit"}
    }

For more information, refer to $group and $sum.

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

Executing PHP code from a list item

On one of my website pages, I have a list that functions as a delete button. However, I am interested in making it so that when a user clicks on the delete option, a php script is triggered - similar to how a submit button works. Below is the list structu ...

I am getting NaN as the output from my function, but I am unsure of the reason behind

For pracitce, I have created this code to calculate the total amount spent on gas and food using arrays. However, I am encountering an issue where it is returning NaN. const gas = [20, 40, 100]; const food = [10, 40, 50]; function total(gas, food) { ...

The transition between backgrounds is malfunctioning

I want to create a smooth transition effect for changing the background of an element within a setInterval function. Currently, the background changes immediately, but I would like it to transition over a period of time. var act = true; setInterval(func ...

When attempting to call Firebase Functions, ensure that Access-Control-Allow-Origin is set up correctly

Although it may seem straightforward, I am confused about how Firebase's functions are supposed to work. Is the main purpose of Firebase functions to enable me to execute functions on the server-side by making calls from client-side code? Whenever I t ...

Removing repetitive strings from an array in the most efficient manner

We've successfully developed a script to eliminate duplicate strings from an array while preserving the order necessary for angular's ng-repeat loop. It's also important that the remaining elements maintain their original index. scope.feedb ...

Next.js Project Encounters Compilation Error Due to Tailwind CSS Custom Class

I am currently working on a Next.js project and incorporating Tailwind CSS. Unfortunately, I have come across a compilation error that I am struggling to resolve. The error specifically pertains to a custom utility class that I defined in my theme.css file ...

Form_Open will automatically submit - Ajax Submission in CodeIgniter

I am facing an issue with submitting my form via Ajax. Despite setting up a function to prevent the page from refreshing upon submission, it seems like the form still refreshes the page every time I click submit. I even tried creating a test function to lo ...

Leveraging ng-hide in Angular to show or hide elements based on the state

Is there a way to utilize the ng-hide directive based on the value selected in a dropdown menu? Specifically, I am looking to display #additional-option if option C is chosen from the dropdown list. <div class="form-group"> <label class="co ...

Looping through a JSON object in Highcharts to populate data series

I'm brand new to Java Script and I'm on a mission to loop through my JSON object and populate the Highcharts data series. You can take a look at my static demonstration of what I'm trying to achieve on JS Fiddle. Check out JsFiddle here Any ...

Execute JavaScript code prior to sending a Rails form

Before submitting the form, I would like to trigger the html5 geolocation javascript code. Here's how I envision the process: upon form submission, the user is prompted with a geolocation popup. After allowing access, the form data should be processed ...

The jQuery script automatically triggers submission on its own

Does anyone have an idea why the form auto-submits itself? I can't figure out why it's doing that. I'm using query parsley to validate the form in a modal. When a user opens the modal and starts typing in the text area, they must type at l ...

Leveraging weather application programming interfaces

I am trying to set up a basic webpage that can display tide information from wunderground.com. However, for some reason I am not seeing any results on the page. I have included the load function in hopes of at least getting something to appear when the p ...

Combining two Unix timestamps into a single value

Looking for a way to condense a date range into GET parameters for my application, I pondered the possibility of encoding two Unix timestamps into a single parameter to minimize URL length. While a basic CSV of two timestamps would suffice, my aim is to f ...

Sequelize Inserting Data Exclusively into Child Table with BelongsTo Association

I am facing an issue with my database schema involving the Users and Doctors models. In this setup, the Doctors model has a belongsTo() constraint on the Users. module.exports = (sequelize, DataTypes) => { const Doctors = sequelize.define('Docto ...

What is causing my for/in loop to return null results, while the regular for loop works perfectly fine? (VISUALS included)

My goal is to iterate through an array of objects using a for/in loop in order to log specific properties of each object to the Chrome dev console. However, I am encountering issues as I keep getting null values. As a workaround, I attempted to use a regul ...

JQuery - Select element by clicking outside

I'm trying to figure out how to hide an element when clicking outside of it. Found a solution at: https://css-tricks.com/dangers-stopping-event-propagation/ $(document).on('click', function(event) { if (!$(event.target).closest('#m ...

Limiting the scope of the jQuery scrollToFixed functionality within various nested DIV elements

I have been grappling with this issue for the past two days without success. I am utilizing the ScrollToFixed plugin from https://github.com/bigspotteddog/ScrollToFixed and my goal is to restrict the fixed positioning within a parent DIV. Despite scouring ...

Pressing on ListView (Android) elements will send data to the mySQL server at the remote school

I have a mobile application that utilizes the Zxing barcode scanner in order to scan inventory items such as computers and equipment. Once scanned, the barcode can be inputted into a text field. Following this, I am able to input additional data for the sc ...

The Autocomplete feature from the @react-google-maps/api component seems to be malfunctioning as it returns

I'm encountering some difficulties with the Autocomplete component in @react-google-maps/api. While Autocomplete is working and displaying options, clicking on an option fills the input box but I'm only getting 'undefined' from the Plac ...

Updating data in MongoDB with an expiration feature

Despite setting the expireAfterSeconds option to 60 in my Mongodb shell, my new entries in the unlock schema are not being deleted after 60 seconds. db.unlocks.ensureIndex( { "createdAt": 1 }, { expireAfterSeconds: 60 } ) Here is the structure of my Sche ...