Ways to retrieve records within a specified date range in MongoDB?

I have a data record in my mongodb collection with the field "birth_date" set to "1983-05-06T16:26:32.613Z".

Below is the find query I used to retrieve this record within a specific date range:

var birthYear = 1983;
var birthDateStart = new Date('1.1.' + birthYear); 
var birthDateEnd = new Date('12.30.' + birthYear); 
    var cursor = db.collection('users').find({
            birth_date: {$gte: birthDateStart, $lt: birthDateEnd}
        })

It seems like the issue lies in the date format. How can I get the same Date() format as the one stored in the database?

I utilized variety tool to analyze the DB schema:

+--------------------------------------------------+
| key          | types    | occurrences | percents |
| ------------ | -------- | ----------- | -------- |
| _id          | ObjectId |           1 |    100.0 |
| bio          | String   |           1 |    100.0 |
| birth_date   | String   |           1 |    100.0 |
+--------------------------------------------------+

As I am using the 'mongodb' package for express.js, I encountered an error when trying to use ISODate().

ReferenceError: ISODate is not defined

Answer №1

Appreciate all the hints provided. The main issue was that the field birth_date was being saved as a String.

This answer aims to demonstrate how to convert a field from String to Date format for all records in your collection, and also how to search by Age (in years) when only the birthdate is saved. Hopefully, this will benefit others facing a similar challenge.

To change the format of the field 'birth_date' from String to Date:

mongo.connect(url, function (err, db) {
        console.log(err);
        var resultArray = [];
        var cursor = db.collection('users').find({});
        cursor.forEach(function (doc, err) {
            console.log(doc);
            db.collection('users').update({_id: doc._id}, {$set: {birth_date: new Date(doc.birth_date)}});
        }, function () {
            db.close();
            res.send("Done!");
        })
    })

Search for a user who is 18 years old:

var search_age = 18;
var birthYear = new Date(Date.now()).getFullYear() - search_age;
var birthDateStart = new Date(birthYear, 0, 1);
var birthDateEnd = new Date(birthYear, 11, 31, 23, 59, 59, 999);
var resultArray = [];

mongo.connect(url, function (err, db) {
    console.log(err);
    var resultArray = [];
    var cursor = db.collection('users').find({
            birth_date: {$gte: birthDateStart, $lt: birthDateEnd},
        });
    cursor.forEach(function (doc, err) {
        resultArray.push(doc);
    }, function () {
        db.close();
        res.send(resultArray);
    });
})

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

Struggling to set up an HTTPS server with Express and Node.js - it just won't start

I'm attempting to configure HTTPS with express.js for node, but I am encountering issues getting it to work. Below is the code from my server.js file: const fs = require('fs'); const http = require ('http'); const https = require( ...

Tips for efficiently storing and managing large data volumes in real-time applications

I am currently developing a real-time collaborative canvas project. Users have the ability to create rooms and invite others to join with a specific ID and password. The application also supports multiple tabs and utilizes fabric.js for handling canvas ope ...

I'm encountering an issue where I receive the error `Cannot read property 'map' of undefined` while attempting to integrate the backend with React. What could be causing this error and how

I'm currently learning React and I've been using a tutorial here to connect my database to the front end of my React application. Unfortunately, every time I try running 'npm start' at 'localhost:3000' in express-react/backend ...

Labeling src library files with namespaces

I have developed a ReactJS website that interacts with a library called analyzejs which was created in another programming language. While I am able to call functions from this library, I do not have much flexibility to modify its contents. Up until now, ...

Sliding with JavaScript

I'm looking to develop a unique web interface where users can divide a "timeline" into multiple segments. Start|-----------------------------|End ^flag one ^flag two Users should be able to add customizable flags and adjust their position ...

What is the process for creating a list using layers that are published in Geoserver?

I am currently working on developing a webmapping application. One of the tasks I need to accomplish is parsing the WMS request in order to retrieve the title of each layer within the layers section: var xhr = new XMLHttpRequest(); xhr.open(' ...

The definition of Csrftoken is missing

The code I am currently using, as per the recommended documentation, is: function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); ...

The functionality of HTML5 canvas image objects is not functioning as expected

I have been working on a function to retrieve an image object using HTML5 canvas, but I keep encountering an error alert (onerror event) function FetchImage() { var img = new Image(); img.src = "http://localhost/assets/images/loadedsprite.png"; ...

Opting for PHP over JSON for the instant search script output

Is there a way to modify my Google Instant style search script, written in jQuery, to retrieve results from a PHP script and output PHP-generated HTML instead of JSON? Below is the current code: $(document).ready(function(){ $("#search").keyup(functi ...

Tips for creating a sophisticated state transition diagram using Typescript

If you have a creative idea for a new title, feel free to make changes! I have two enums set up like this: enum State { A = "A", B = "B", C = "C" } enum Event { X = "X", Y = "Y", Z ...

Button will be disabled unless a value is selected in the dropdown menu

I am currently dealing with a code issue where the button is disabled on page load when the dropdown value is empty. However, even after selecting a value from the populated database dropdown, the button remains disabled. Jquery: <script> $(doc ...

Do you always need to use $scope when defining a method in Angular?

Is it always necessary to set a method to the $scope in order for it to be visible or accessible in various parts of an application? For example, is it a good practice to use $scope when defining a method that may only be used within one controller? Consid ...

Issue with React Testing Library: Attempting to access the 'contents' property of an undefined value in Redux

Hello, I'm new to writing test cases using React Testing Library. Below is the code of my component: import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; ...

Leveraging the package.json file for client-side packages, enabling them to be dynamically loaded in the browser

Considering expanding the structure of package.json to incorporate dynamic package (plugin) loading on the client side. I am curious about how this idea aligns with the vision of npm. Essentially, I am interested in loading multiple modules with shared met ...

Tips for generating a <div> element with multiple children using a loop

section, I have configured a div element with a class named div class = "postWindow". When it comes to the HTML code, here is an example: <div class = "postWindow"> <div class = "userName">Initial Name</div> <div class = "p ...

Utilize React-markdown to interpret subscript text in markdown format

I tried to create subscript text in an .md file using the following syntax: x_i x~i~ Unfortunately, react-markdown did not interpret this as subscript. After some research, I discovered the package remark-sub-super and implemented it with the plugin ...

Is there a way to transform MongoDB Controller elements into JSON using perl?

require 'MongoDB'; my $info = $db->items->find('something'); my $json_data; while($info->next){ add the information to a $json_data } In search of a solution my @items = $info->all; foreach (@items){ ...

Generating a dynamic sitemap with Next.js

I have been working on a project where I need to create a sitemap, and I am currently using next-sitemap for generation. However, I've encountered an issue with this method, as well as other solutions I've come across, because the sitemap is only ...

What is the best way to ensure that the swf loads only after all the images and text have loaded completely

Is there a way to use jQuery to control the loading of SWF files on my CMS system? Sometimes when a video is included in the SWF file, it uses up bandwidth and makes the page non-responsive for a while. I would like the SWF files to load after the other co ...

The difference between using an event listener directly in HTML vs. using the add

Looking to customize the behavior of an HTML element using event listeners? There are two ways to accomplish this: <form class="my-form"> <input type="submit"/> </form> <script> document.querySelectorAll(&quo ...