[英]How to group an array of documents to arrays of arrays using the aggregation pipeline in Mongodb?
[英]How to use $dateToString in $group pipeline Mongodb Aggregation?
我正在使用Mongodb 3.0,我想使用$dateToString
以特定格式使用,例如Thu 10-Nov-2016
。 这是我的代码
collection.aggregate([
{
$group: {
_id: {
month: { $month: "$onDate" },
day: { $dayOfMonth: "$onDate" },
year: { $year: "$onDate" }
},
totalSearch: { $sum: 1 }
}
},
{ $limit: 10 },
{ $sort: { '_id.year': -1,'_id.month': -1,'_id.day': -1 } },
//***Here i am want to use $dateToString with $project corresponding to $group._id****////
{ $project: { $dateToString: { format: 'xxxxxxxx', date: xxxxxxxxx } } }
],
function(err, dayWise) {
if (err)
cb(err);
console.log('dayWises',dayWise);
cb(null, dayWise);
}
)
您可以在项目阶段添加$ concat以从组ID日期值中获取日期字符串,以格式化日期字符串。
{
$project: {
'value': {
'$concat': [{
$substr: ["$_id.year", 0, -1]
},
"-", {
$substr: ["$_id.month", 0, -1]
},
"-", {
$substr: ["$_id.day", 0, -1]
}
]
}
}
}
或者,您可以将$ dateToString以及其他值作为id应用于组管道中。
{
$group: {
_id: {
month: {
$month: "$onDate"
},
day: {
$dayOfMonth: "$onDate"
},
year: {
$year: "$onDate"
},
formattedDateString: {
$dateToString: {
format: "%Y-%m-%d",
date: '$onDate'
}
}
},
totalSearch: {
$sum: 1
}
}
我认为您无法获取您指定的格式,相反,您可以获取“ 2014-01-01”这种格式,在您的小组讨论中,尚未通过日期的ISO中的第一个与dateTostring一起使用,请选中
collection.aggregate([{
$group: {
_id: { month: { $month: "$onDate" }, day: { $dayOfMonth: "$onDate" }, year: { $year: "$onDate" } },date : {"$first":"$onDate"}
totalSearch: { $sum: 1 }
},
},
{ $limit: 10 },
{ $sort: { '_id.year': -1,'_id.month': -1,'_id.day': -1 } },
{$project:{$dateToString:{format:"%Y-%m-%d",date: $onDate}}
}
],
function(err, dayWise) {
if (err)
cb(err);
console.log('dayWises',dayWise);
cb(null, dayWise);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.