以下是一个使用MongoDB MQL(MongoDB查询语言)解决这个问题的示例代码:
db.collection.aggregate([
{
$group: {
_id: {
year: { $year: "$date" },
month: { $month: "$date" },
day: { $dayOfMonth: "$date" },
otherField: "$otherField"
},
count: { $sum: 1 }
}
},
{
$project: {
_id: 0,
year: "$_id.year",
month: "$_id.month",
day: "$_id.day",
otherField: "$_id.otherField",
count: 1
}
}
])
上述代码使用aggregate
方法对集合进行聚合操作。首先,使用$group
阶段按照日期和其他字段对文档进行分组,并使用$sum
操作符计算每个组的计数。然后,使用$project
阶段重新组织结果,以便显示年、月、日、其他字段和计数。最后,使用$project
阶段将_id
字段设置为0,以排除默认的_id
字段。
请注意,您需要将代码中的collection
替换为实际的集合名称,date
替换为实际的日期字段名称,otherField
替换为实际的其他字段名称。
上一篇:按日期分组并取最后一行