将ISO日期转换为yyyy-mm-dd格式 [英] Convert ISO date to yyyy-mm-dd format
问题描述
给出集合(#name:用户)结构:
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")
}
]
}
我想根据用户名字段查询此集合,并以"yyyy-mm-dd"格式返回ts. 预期输出:
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"
}
]
}
我尝试过这样的事情:
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.
推荐答案
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"
}}
}
}
])
对于MongoDB 3.4和更高版本,您可以使用新的 $map
即可创建数组字段,而无需展开和分组:
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"
}
}
}
}
}
}
}
])
这篇关于将ISO日期转换为yyyy-mm-dd格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!