Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement $dateToString on array items with MongoDB
To implement $dateToString on array items, use aggregate() in MongoDB. Let us create a collection with documents −
> db.demo104.insertOne(
... {
...
... "AppName" : "Online Book",
... "Details" : [
... {
... "ClientName" : "Chris",
... "Deadline" : new ISODate("2020-03-10")
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2ed7fd9fd5fd66da21446f")
}
Display all documents from a collection with the help of find() method −
> db.demo104.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e2ed7fd9fd5fd66da21446f"),
"AppName" : "Online Book",
"Details" : [
{
"ClientName" : "Chris",
"Deadline" : ISODate("2020-03-10T00:00:00Z")
}
]
}
Following is the query to implement $dateToString on array items −
> db.demo104.aggregate([
... { "$match": {}},
... { "$project": {
... "title": 1,
... "Details": {
... "$map": {
... "input": "$Details",
... "as": "out",
... "in": {
... "ClientName": "$$out.ClientName",
... "Deadline": {
... "$dateToString": { "format": "%m", "date": "$$out.Deadline" }
... }
... }
... }
... }
... }}
... ])
This will produce the following output −
{ "_id" : ObjectId("5e2ed7fd9fd5fd66da21446f"), "Details" : [ { "ClientName" : "Chris", "Deadline" : "03" } ] }Advertisements