Convert ISO date to yyyy-mm-dd format

19,098

Consider running an aggregation pipeline that will allow you to flatten the data list first, project the new field using the $dateToString operator, then regroup the flattened docs to get your desired result.

The above can be shown in three distinct pipelines:

db.users.aggregate([
    { "$match": { "username": "xyz" } },
    { "$unwind": "$followers" },
    {
        "$project": {
            "username": 1,
            "count": "$followers.count",
            "date": { "$dateToString": { "format": "%Y-%m-%d", "date": "$followers.ts" } }
        }
    },
    {
        "$group": {
            "_id": "$_id",
            "username": { "$first": "$username" },
            "followers": { "$push": {
                "count": "$count",
                "date": "$date"
            }}
        }
    }
])

With MongoDB 3.4 and newer, you can use the new $addFields pipeline step together with $map to create the array field without the need to unwind and group:

db.users.aggregate([
    { "$match": { "username": "xyz" } },    
    {
        "$addFields": {
            "followers": { 
                "$map": { 
                    "input": "$followers", 
                    "as": "follower",
                    "in": { 
                        "count": "$$follower.count", 
                        "date": { 
                            "$dateToString": { 
                                "format": "%Y-%m-%d", 
                                "date": "$$follower.ts" 
                            }
                        } 
                    } 
                } 
            }
        }
    }
])
Share:
19,098
Veer
Author by

Veer

Updated on June 22, 2022

Comments

  • Veer
    Veer almost 2 years

    Given collection(#name: users) Structure:

    {
    "_id" : ObjectId("57653dcc533304a40ac504fc"),
    "username" : "XYZ",
    "followers" : [ 
        {
            "count" : 31,
            "ts" : ISODate("2016-06-17T18:30:00.996Z")
        }, 
        {
            "count" : 31,
            "ts" : ISODate("2016-06-18T18:30:00.288Z")
        }
    ]
    }
    

    I want to query this collection based on username field, and ts to be returned in 'yyyy-mm-dd' format. Expected Output:

    {
    "_id" : ObjectId("57653dcc533304a40ac504fc"),
    "username" : "XYZ",
    "followers" : [ 
        {
            "count" : 31,
            "date" : "2016-06-17"
        }, 
        {
            "count" : 31,
            "date" : "2016-06-18"
        }
    ]
    }
    

    I have tried something like this:

    db.users.aggregate([
    {$match:{"username":"xyz"}},
    {$project:{ "followers":{"count":1,
            "date":"$followers.ts.toISOString().slice(0,10).replace(/-/g,'-')"
              }}
    }
    ])
    

    But it doesn't seems to be working. Can anyone please help? Thanks much.