- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to convert the field value and create datetime day of month during projection?
To convert filed value to create datetime day of month, use MongoDB aggregate(). Let us create a collection with documents −
> db.demo209.insertOne( ... { ... "_id" : "101", ... "details" : [ ... { ... "dat" : 1528929908, ... "Name" : "Chris" ... }, ... { ... "dat" : 1529082069, ... "Name":"Carol" ... } ... ], ... "Age" : 25, ... "CountryName" : "US" ... } ...); { "acknowledged" : true, "insertedId" : "101" }
Display all documents from a collection with the help of find() method −
> db.demo209.find().pretty();
This will produce the following output −
{ "_id" : "101", "details" : [ { "dat" : 1528929908, "Name" : "Chris" }, { "dat" : 1529082069, "Name" : "Carol" } ], "Age" : 25, "CountryName" : "US" }
Following is the query to convert the field value and create datetime day of month during projection −
> db.demo209.aggregate({ ... "$unwind": "$details" ... }, { ... "$project": { ... "Age": 1, ... "CountryName": 1, ... "Name": "$details.Name", ... "DayOfMonth": { ... "$dayOfMonth": { ... "$add": [new Date(0), { ... "$multiply": ["$details.dat", 1000] ... }] ... } ... } ... } ...})
This will produce the following output −
{ "_id" : "101", "Age" : 25, "CountryName" : "US", "Name" : "Chris", "DayOfMonth" : 13 } { "_id" : "101", "Age" : 25, "CountryName" : "US", "Name" : "Carol", "DayOfMonth" : 15 }
- Related Articles
- MongoDB query to search for Month and Day only?
- MongoDB query to search date records using only Month and Day
- How to add a day to datetime field in MySQL query?
- How can I add one day to DATETIME field in MySQL query?
- Convert day of year to day of month in Java
- MongoDB query to create new field and count set the count of another field in it?
- MySQL query to order by current day and month?
- Query MongoDB for a datetime value less than NOW?
- Format MySQL date and convert to year-month-day
- Convert datetime to get month name in MySQL?
- How to extract only the month and day from a datetime object in Python?
- How to convert year, month, and day of the month into a complete date in R?
- How to convert char field to datetime field in MySQL?
- MongoDB query (aggregation framework) to match a specific field value
- Compare only day and month with date field in MySQL?

Advertisements