在 shell 上的 mongodb 查询输出中格式化日期 [英] Format date in mongodb query output on shell

查看:105
本文介绍了在 shell 上的 mongodb 查询输出中格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 mongo shell 输出中将日期时间格式化为特定格式

I want to format the date time into an specific format on the mongo shell output

我的查询

db.getCollection('people').find({
        date: { 
            $gte: ISODate("2017-04-24T14:04:34.447Z") 
        }
    },
    {
        _id: 0,
        age: 0,

    }
);

我针对此查询的输出:

/* 1 */
{
    "user_id" : "bcd020",
    "status" : "D",
    "date" : ISODate("2017-04-24T14:04:34.447Z")
}

/* 2 */
{
    "user_id" : "bcd021",
    "status" : "D",
    "date" : ISODate("2017-04-24T14:04:34.447Z")
}

我想要的是格式化输出中的日期时间,例如

What i want is to format the datetime in the output something like,

/* 1 */
    {
        "user_id" : "bcd020",
        "status" : "D",
        "date" : 2017-04-24 14:04:34
    }

    /* 2 */
    {
        "user_id" : "bcd021",
        "status" : "D",
        "date" : 2017-04-24 14:04:34
    }

推荐答案

解决方案正在使用聚合管道,如 Veeram 在评论部分中所述

Solution is using aggregation pipeline as stated by Veeram in comments section

db.getCollection('people').aggregate([
    {
        $project:{
            datetime: {$dateToString: {format: "%G-%m-%d %H:%M:%S",date: "$datetime"}},
            age : 1
        }
    }
]);

这篇关于在 shell 上的 mongodb 查询输出中格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆