Tips for composing a single aggregation within a query

In my query, I wanted to find the first record with a CREATE_DATE greater than or equal to a specific date and less than another date. After calculating the duration between these dates, I needed to write another query. However, I was unsure how to combine these queries into a single aggregation query.

Query 1

db.lights.aggregate({
  $match: {
    CREATE_DATE: {
      $gte: ISODate("2018-01-24T20:05:30.000Z"),
      $lt: ISODate("2018-02-24T20:05:30.000Z")
    }
  }
});

Result

{
  "_id": ObjectId("5a9a74843711955836a8b4b5"),
  "SWITCHID": "Z4-W40-SS451A/4",
  "CREATE_DATE": ISODate("2018-01-24T20:05:30Z"),
  "RECEIVEDDATE": ISODate("2018-02-24T20:05:45Z"),
  "STATUS": "LIGHTS ON"
}

Query 2

db.lights.aggregate([
  {
    $addFields: {
      offduration: {
        $divide: [
          {
            $subtract: [
              "$RECEIVEDDATE",
              "$CREATE_DATE"
            ]
          },
          3600000
        ]
      }
    }
  }
]);

Result

{
  "_id": ObjectId("5a9a75af3711955836a8b4c8"),
  "SWITCHID": "Z4-W40-SS451A/5",
  "CREATE_DATE": ISODate("2018-02-24T20:05:30Z"),
  "RECEIVEDDATE": ISODate("2018-02-24T20:05:45Z"),
  "STATUS": "LIGHTS ON",
  "offduration": 0.004166666666666667
}

Answer №1

Make sure to enhance your query in the following manner:

db.lights.aggregate({
  $match: {
  CREATE_DATE: {
    $gte: ISODate("2018-01-24T20:05:30.000Z"),
    $lt: ISODate("2018-02-24T20:05:30.000Z")
    }
  }
},
 {
  $addFields: {
    offduration: {
      $divide: [
        {
          $subtract: [
            "$RECEIVEDDATE",
            "$CREATE_DATE"
          ]
        },
        3600000
      ]
    }
  }
},
{
$project: {
  _id: 1,
  SWITCHID: 1,
  CREATE_DATE: 1,
  RECEIVEDDATE: 1,
  STATUS: 1,
  offduration: '$offduration',
  avgduration: { $avg: "$offduration" }      
 }
});

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

Showing validation for arrays with multiple inputs using Ajax in the Laravel framework

Could someone please provide guidance on how to use ajax to display the JSON response of form validation messages in Laravel? Below are some of my form inputs: {!! Form::text('stories[0][subject]', null, [ 'class' => 'form-con ...

employ the inverse Euler application

var a = new THREE.Euler( 0, 1, 1.57, 'YXZ' ); var b = new THREE.Vector3( 1, 0, 1 ); var c = b.applyEuler(a); In order to get the value of c using b.applyEuler(a), I am looking for the reverse operation involving applyEuler. Given that the value ...

Encountered a connection error in the Spring Boot application: net::ERR_CONNECTION_REF

Currently working on a school project developing a Spring Boot application using Restful. The application runs smoothly locally, but when deployed to AWS, I am encountering an "net::ERR_CONNECTION_REFUSED" error for all my GET and POST requests sent to the ...

Steps to assign a value to an input element using the state in a React application

Hey there, I hope everything is going well for you! I have a question regarding setting the value of an input field based on the state received from props. I've tried to populate the input with data from the "profile" state using placeholders, but it ...

Iteratively traverse the object to establish connections between parent and child elements

I've been working on creating a recursive function with some guidance I received here: looping through an object (tree) recursively The goal is to traverse the object 'o' and generate a new one where each key is associated with its parents ...

Viewing Server Logs in a Discord Channel

My gaming server stores logs in .txt format, and I'm looking for a way to automatically send updates to a Discord channel whenever there is new log data. I am currently developing a Discord bot using Node.js. Does anyone have any suggestions on how I ...

What could be the reason for the failure of calling a function within an object using "this.myFunction"?

Reviewing these two code snippets, I am faced with a puzzle. The first code block fails to execute, while the second one successfully runs. This has left me perplexed, and I am seeking clarification from those who can shed some light on the matter. [My cu ...

Is it feasible to invert the order of arguments in async.apply?

According to the async documentation: apply(function, arguments..) Creates a function continuation with certain arguments already applied. This can be useful when combined with other control flow functions. Any additional arguments passed to the returned ...

Using AngularJS routing with an Express 4.0 backend API

Recently, I began working on an application utilizing Express 4.0 server. Following a tutorial on scotch.io (http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4), I structured the routes to support a backend api serving an An ...

I am unable to include a new field in my MongoDB document while working with Next.js

I am trying to enhance my document by adding a new field (company). The code snippet below showcases my entire API setup: import { connectToDatabase } from "../../utils/mongodb"; import { getSession } from 'next-auth/client' export de ...

Turning $.post into $.ajax: A step-by-step guide

I need help with converting my $.post code to $.ajax. Here is the code snippet: $.post("../admin-login", { dataName:JSON.stringify({ username:uname, password:pass, }) }, function(data,status){ console.log("Data:"+data); answer = data; ...

There is no response provided by the function

Here is the code for inserting data into the database. However, it seems to be going into the else section as the response is empty. I have checked by alerting the response, but it remains empty. // Function to add donation via AJAX function ccjkfound ...

Press the button using the spacebar

I am facing an issue where I have a button with an anchor element that I need to trigger with the spacebar key for accessibility purposes. However, instead of triggering the button, pressing the spacebar causes the page to jump down when the button is in f ...

React encountered an issue: each child element within a list must be assigned a unique "key" prop

I am feeling a bit puzzled as to why I keep getting the error message: child in a list should have a unique "key" prop. In my SearchFilterCategory component, I have made sure to add a key for each list item using a unique id. Can you help me figu ...

At times, the AngularJS directive may not be invoked

Here is my custom directive: ppm.directive('focusMe', function($timeout) { return { link: function(scope, element, attrs) { scope.$watch(attrs.focusMe, function(value) { if(value === true) { console.log(& ...

How to efficiently locate the latest document in multiple MongoDB groups

I am currently working with a MongoDB database that contains two collections: chats: { chat_id: string, // indexed 1, unique last_updated: number, // indexed -1 // other data... } messages: { chat_id: string; // indexed 1 message_id: string; // ...

Access and retrieve images directly from the output of an s3 bucket query

I've manually uploaded an image named userImage.png, but I'm unsure how to convert the incoming body of the result into an image. While I found some examples in this question[ how to retrieve image from s3 with nodejs ], I'm not sure how to ...

Guide on viewing chromedriver logs during Protractor testing

I've recently discovered that chromedriver has the ability to generate a logfile (https://sites.google.com/a/chromium.org/chromedriver/logging) While the process of setting up this feature when running the executable directly is clear: chromedriver. ...

Encountering a build error with Ubuntu, Node-Gyp, and Canvas – help needed!

Hey there, I'm having some trouble with installing the Canvas package. I've tried Package Versions 6.1.13 and 6.1.3 Here are my system details: Ubuntu 18.04.5, Node 12.18.4 LTS, Python 2.7, g++ installed, pkg-config installed, libjpeg installed ...

Guide to fetching and displaying a complex array API using JavaScript's fetch method

Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API: fetch('https://datausa.io/api/data?d ...