Querying MongoDB with a JavaScript file for formatting datetime values

I am utilizing mongodb3.0.5 and my database collection appears as follows:

{
    "_id" : "xxxxxxxxxxxxxxx",
    "SchoolId" : 1,
    "ActivationTimestamp" : ISODate("2015-09-22T13:01:58.000Z"),
    "PersonDetails" : [ 
        {
            "Name" : "John",
            "AddressZone" : 6,
        }, 
        {
            "Name" : "Mary",
            "AddressZone" : 5,
        },
    ],
    "CreationTimestamp" : ISODate("2015-11-10T10:55:00.009Z")
}

My javascript file is structured like so:

var printData = function(doc){
        print(doc.CreationTimestamp+","+doc.SchoolId+","+doc.PersonDetails.Name+","+doc.PersonDetails.AddressZone)
    };

var cur = 
    db.test.aggregate([
        {$match: {_id: "xxxxxxxxxxxxxxx"}},
        {$unwind: '$PersonDetails'}]);

cur.forEach(printData);

When I execute this command:

.\mongo localhost/test test.js > output.txt

The resulting output (only showing a sample) is:

Tue Sep 22 2015 14:01:58 GMT+0100 (GMT Daylight Time),1,John,6

However, I want the date to be displayed in the format of:

22/09/2015 14:01:58

Is there a method or solution to format the datetime as indicated above?

Answer №1

If you want to work with the date in JavaScript, you can easily do so by creating a new Date object:

var currentDate = new Date(document.CreationTimestamp);

Once you have the date object, you can manipulate it as needed. Here is an example of formatting the date:

var formattedDate = currentDate.getDate() + '/' + (currentDate.getMonth() + 1) + '/' + currentDate.getFullYear() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes() + ':' + currentDate.getSeconds();

To explore more functions that can be called on a date object, visit http://www.w3schools.com/jsref/jsref_obj_date.asp.

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

Updating information in the third tier of a mongo database

Struggling to find a solution for editing nested data beyond the 2nd level in my model structure: var Category = new Schema({ name: String, url: String, id: String }); var Subgroup = new Schema({ name: String, url: String, id: Str ...

What is the process for including an additional button in the DateTimePicker feature of material UI?

I'm currently utilizing DateTimePicker in my React application. I wish to incorporate a Clear button positioned to the left of the Cancel Button. import { MuiPickersUtilsProvider, DateTimePicker } from "@material-ui/pickers"; import DateFnsUtils fro ...

When using jQuery's POST method, the "done" event is triggered, however, no data is being sent

I've been working on implementing AJAX form submission and wrote a function to handle it when the button is clicked: function putUser() { $('button#putUser').on('click', function() { var user = $('input#user' ...

Instantly refreshing the Angular DOM following data modifications and retrieval from the database

I am currently working on a Single Page Application that uses Angular 8 for the frontend and Laravel for the backend. This application is a CRUD (Create, Read, Update, Delete) system. The delete functionality is working as expected, deleting users with spe ...

How can I fetch data from a ManyToMany jointable using Typeorm?

Is there a way to retrieve the categories associated with posts when fetching user data? Data Models: @Entity() export class Category extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Column() name: string; @Column() description: s ...

Display the printed outcome in a fresh window

HTML: <form id="dbview" method="post" action="core/process.php"> .... <p style='text-align:center;'> <input id='delete' type='submit' name='process' value='Delete selected'/> < ...

Explore three stylish ways to showcase dynamic JavaScript content using CSS

Objective: For Value 1, the CSS class should be badge-primary For Value 2, the CSS class should be badge-secondary For all other values, use the CSS class badge-danger This functionality is implemented in the handleChange function. Issue: Current ...

Error message: Please provide an expression with const in React JS component

Can you assist me with this issue? I am trying to determine if the user is registered. If they are registered, I want to display the home URL, and if they are not registered, I want to display the registration URL. To do this, I am checking the saved dat ...

Using jQuery to iterate through JSON data obtained from a web service

In this code snippet, I am attempting to retrieve a JSON response from a PHP page and then iterate through it to display the name field of each JSON object. However, for some reason, nothing is being alerted out. <html> <head> <title>A ...

Difficulties with managing button events in a Vue project

Just getting started with Vue and I'm trying to set up a simple callback function for button clicks. The callback is working, but the name of the button that was clicked keeps showing as "undefined." Here's my HTML code: <button class="w ...

What is the best way to conceal a callback form once it has been successfully submitted?

In my callback form, everything seems to be functioning properly. However, there is a slight issue when the client hits the submit button multiple times. Each time they do so, a notification saying "Your request sent successfully" pops up next to the butto ...

Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific ho ...

How to Properly Implement app.use() in Express for Middleware

What is the reason behind some middleware functions being passed in with invocation parentheses, while an anonymous function is passed in without being invoked? app.use(logger()); app.use(bodyParser()); If logger() is evaluated immediately and the return ...

Incorporate a binary document into a JSPdf file

I am currently utilizing JsPDF to export HTML content into a downloadable PDF. Explore the following example which involves taking some HTML content and generating a downloaded PDF file using JsPdf import React from "react"; import { render } fro ...

Encountering a 400 error when utilizing the Google Translate free API with Curl

I am attempting to utilize the free Google Translate API that is derived from Firefox's S3 Google Translator addon, by incorporating the following code: https://translate.google.com/translate_a/single?client=t&sl=auto& tl=en&hl=en&dt= ...

MongoDB Aggregation: Obtaining the group _id alongside the total number of records

Dealing with a massive MongoDB collection laden with duplicate keys is proving to be quite a challenge for me. I frequently run aggregation queries to pinpoint these duplicates and analyze their differences. The sheer size of the database, coupled with in ...

Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I ...

maximum number of results in google custom search limit

I'm trying to retrieve the top 40 results from the Google API, but when I limit the result using the code below, it doesn't seem to work. How can I achieve getting the top 40 results with the Google API? <script> (function() { ...

How can you establish a default value on a paper select in Polymer?

I have a paper-select element that I want to customize with a default value when the page loads or after a specific event occurs. <dom-module id="custom-paper-select"> <template> <paper-select id="select-input-1" multiple ...

Ionic: setInterval/setTimer not functioning after 5 minutes in the background

In need of a timer that can send notifications via the OneSignal API after a user-defined time period is reached. Users can set the timer for any value between 1-59 minutes. Despite attempts to use the background mode plugin, specifically setInterval and s ...