Retrieving information from MongoDB within a specific time range, between a designated start date

Currently, my Mongo database contains JSON data structured like this:

{ 
    "uSN": "100030001",
    "timestamp": 1470009600,
    "timetag": 1082016,
    "monthtag": 82016,
    "hourtag": 11,
    "mintag": 10,
    "yeartag": 2016, 
    "id": "d100030001_01082016_11_10"
  },
  { 
    "uSN": "100030001",
    "timestamp": 1470096000,
    "timetag": 2082016,
    "monthtag": 82016,
    "hourtag": 11,
    "mintag": 10,
    "yeartag": 2016, 
    "id": "d100030001_02082016_11_10"
  },
  { 
    "uSN": "100030001",
    "timestamp": 1469850900,
    "timetag": 30072016,
    "monthtag": 72016,
    "hourtag": 10,
    "mintag": 55,
    "yeartag": 2016, 
    "id": "d100030001_30072016_10_55"
  },
  { 
    "uSN": "100030001",
    "timestamp": 1469923200,
    "timetag": 31072016,
    "monthtag": 72016,
    "hourtag": 11,
    "mintag": 10,
    "yeartag": 2016, 
    "id": "d100030001_31072016_11_10"
  },
  { 
    "uSN": "100030001",
    "timestamp": 1469577600,
    "timetag": 27072016,
    "monthtag": 72016,
    "hourtag": 11,
    "mintag": 10,
    "yeartag": 2016, 
    "id": "d100030001_27072016_11_10"
  }

I'm attempting to query the database from my mongo shell to retrieve data ranging from the 30th of July, 2016 to the 1st of August, 2016.

The queries I've tried so far are:

db.dataProfTable.find({ uSN: '100030001', timestamp : {'$gte': new Date(1469836800), '$lte': new Date(1470009600)})

and
db.dataProfTable.find({'uSN': '100030001', 'timetag': {$gte: '30072016', $lt: '01082016'}})

Unfortunately, these queries are not producing the desired results. How can I resolve this issue?

Answer №1

To create a query using JS dates within the date range "30-07-2016" to "01-08-2016", you can retrieve timestamps in seconds by dividing by 1000:

var start = new Date("2016-07-30")/1000,
    end = new Date("2016-08-01")/1000;
db.dataProfTable.find({
    "timestamp": { "$gte": start, "$lte": end }
})

Output Example

/* 1 */
{
    "_id" : ObjectId("579f04ccd8f31a5788eba0fb"),
    "uSN" : "100030001",
    "timestamp" : 1470009600,
    "timetag" : 1082016,
    "monthtag" : 82016,
    "hourtag" : 11,
    "mintag" : 10,
    "yeartag" : 2016,
    "id" : "d100030001_01082016_11_10"
}

/* 2 */
{
    "_id" : ObjectId("579f04ccd8f31a5788eba0fd"),
    "uSN" : "100030001",
    "timestamp" : 1469850900,
    "timetag" : 30072016,
    "monthtag" : 72016,
    "hourtag" : 10,
    "mintag" : 55,
    "yeartag" : 2016,
    "id" : "d100030001_30072016_10_55"
}

Answer №2

     Give This a Shot!

Why not try:

1.Monthtag :

db.dataProfTable.find({ uSN: '100030001', $and:[ {monthtag : {$gte: 72016}},{monthtag : {$lte: 82016}}]})

2.Timestamp :

db.dataProfTable.find({ uSN: '100030001', $and:[ {timestamp : {$gte: 1469836800}},{timestamp : {$lte: 1470009600}}]})

Answer №3

If you want to search by specific timestamp, follow these steps:

var start = new Date("07/30/2016").getTime()/1000 //Date Format:mm/dd/yyyy. Dividing by 1000 as it is stored in seconds
var end = new Date("08/01/2016").getTime()/1000
db.dataProfTable.find({ uSN: '100030001', $and:[ {timestamp : {$gte:start}},{timestamp : {$lte: end}}]})

If you need to query by timetag, use the code below:

db.dataProfTable.find({'uSN': '100030001', 'timetag': {$gte: 30072016, $lt: 01082016}}) // As timetag is stored as a number

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

Utilizing Mongo / BSON ObjectIDs in Parse Server

I have a project undergoing migration from Parse Server that needs to retain backwards compatibility. Parse Server generates its own object Ids, as opposed to using Mongo's built-in generator. I am curious to know: How does Parse Server generate ...

A guide on organizing dates in a datatable using the dd-MMM-yyyy hh:mm tt format

I have encountered an issue with sorting the date column in my datatable. Here is a screenshot showcasing the problem. Below is the code I am using: <table id="tbl" class="table table-small-font table-bordered table-striped"> <thead> &l ...

Instructions on retrieving basic array information from Firebase and fetching it

Being a beginner, I am currently focusing on learning Firebase instead... Here is a simple HTML code snippet that I created: <div class="container" id="msgs"> </div> I am trying to load data from F ...

Duplicating information within a row

Why am I seeing the same value in all rows of the table? Each row in the table can be clicked to reveal additional information, but every row displays the data from the last clicked row. This issue may be due to saving data in the same object. Unfortunatel ...

Unable to choose flash element with jQuery swfobject

When attempting to embed a flash object using swfobject, I am encountering an issue. Once the object is rendered, the following code does not appear to select the flash object itself; instead, it only targets the div element that was present prior to rende ...

Build a Node.js application with Express to host static files

I am attempting to provide my static files "web.html" and "mobile.html", but I want them to be served only if the user is accessing from a web or mobile device. After some research, I came up with this code: var express = require('express'); va ...

Uploading videos to a single YouTube channel using the YouTube Data API

I have been tasked with creating a node js app for a select group of individuals who need to upload videos. However, our budget is quite limited and we are unable to afford cloud storage services. I am curious if it would be feasible to create a key syste ...

What is the best method for extracting attribute values from multiple child elements using puppeteer?

When using this code, I can retrieve the attribute value of the first element selected. By adding /html/body/section/div[3]/img<2> or img<3> in the xpath, I am able to retrieve data for subsequent img elements. However, the parent element on t ...

C# implementation of the btoa function from JavaScript

I am in need of assistance recoding a JavaScript function to C# that makes use of the btoa method to convert a string of Unicode characters into base64. The challenge lies in ensuring that the encoding used in both languages is identical, as currently, the ...

What techniques can be utilized to obscure Tailwindcss HTML class names when deploying to production?

Is there a way to camouflage the HTML classnames in production while utilizing Tailwindcss? My current setup involves React.js and CRACO, following the guidelines provided in Tailwind's documentation. ...

Tips for fetching the chosen choices from a drop-down menu and then performing multiplication with input fields

Hey there! I'm attempting to create a system that checks if the user has selected an item from a dropdown menu, and based on their selection, perform a multiplication operation with three different variables and display the result. For instance, if " ...

Establishing a connection to MongoDB Atlas using Golang's mgo library seems to be a challenge due to a persistent issue

I am facing an issue with connecting to a replica set from MongoDB Atlas. I have tried using various languages and the regular mongo client, but no matter what URL format I use - like this one: mongodb://user:<a href="/cdn-cgi/l/email-protection" class= ...

Is it possible to update an object's field within an array in a Mongo collection using meteor.js?

I attempted to utilize the positional $ operator in order to update a field within an object in an array, following the example provided in the Mongo documentation (docs.mongodb.com/manual/reference/operator/update/positional/). However, I encountered an i ...

Iterate through the URL parameters and store them in the database

I need to efficiently loop through all my post requests and aggregate them collectively. What is the most effective approach for achieving this? Below is the Form structure along with the data I receive: var Form = new Schema({ title: { type: ...

Using `on('click') in JQuery has a one-time effect

Although there are many questions similar to this one, I am still having trouble figuring it out. <div class="message"></div> <button id="getMessage">Get Quote</button> $.getJSON("http://quotesondesign.com/wp-json/posts?filter[or ...

Is there a way to determine where a Javascript event originated from when it was triggered programmatically?

In my current debugging situation, I am investigating why pressing Enter on a submit button triggers a 'click' event on that same button. It appears that the click event is being fired programmatically, which is the expected behavior in the appli ...

The error "NotRegistered" is thrown by Mongoengine when encountering a cyclic reference and reverse_delete_rule in

The code snippet below demonstrates a scheme and a tag, where a scheme represents a tree of tags. from mongoengine import * class Scheme(Document): #_id = None # provided by mongodb name = StringField(max_length=120, required=True) tags = L ...

The Intersection Observer encountered an issue as it was unable to access the property 'current' since it was undefined

My current project involves the implementation of IntersectionObserver, but I am facing an issue where I receive the error message Cannot read property 'current' of undefined. Can anyone help me identify what might be causing this problem? useOn ...

Trouble encountered with JSX in my custom React Library after transitioning to Preact

I've created a straightforward React library that I implement with my own state management, utilizing just a Higher Order Component: import React from 'react'; const connect = (state, chunk) => Comp => props =>{ const newProps ...

Eliminate viewed alerts by implementing a scrolling feature with the help of Jquery, Javascript, and PHP

My goal is to clear or remove notifications based on user scrolling. The idea is to clear the notification once the user has seen it, specifically in a pop-up window for notifications. I am relatively new to Javascript/jQuery and feeling a bit confused abo ...