node.js - 在mongodb中按月份和日期分组并显示列表
问题描述
我的数据库产品架构结构
{ "_id" : "507d95d5719dbef170f15bf9" , "name" : "AC3 Series Charger", "type" : "accessory", "price" : 19,"created":"1626083461034"}
{ "_id" : "507d95d5719dbef170f15bfa" , "name" : "AC3 Case Green", "type" : "case" , "price" : 12, "created":"1625805979235"}
{ "_id" : "507d95d5719dbef170f15bfb" , "name" : "Phone Extended Warranty", "type" : "warranty", "price" : 38,"created":"1624374320653" }
{ "_id" : "507d95d5719dbef170f15bfc" , "name" : "AC3 Case Black", "type" : "case" , "price" : 12.5,"created":"1624606153646" }
{ "_id" : "507d95d5719dbef170f15bfd" , "name" : "AC3 Case Red", "type" : "case" , "price" : 12, "created":"1624362066717"}
{ "_id" : "507d95d5719dbef170f15bfe" , "name" : "Phone Service Basic Plan", "type" : "service", "price":9.5,"created":"1624446320186"}
{ "_id" : "507d95d5719dbef170f15bff" , "name" : "Phone Service Core Plan", "type" : "service", "price" :3.5,"created":"1624605403064"}
{ "_id" : "507d95d5719dbef170f15c00" , "name" : "Phone Service Family Plan", "type" : "service", "price":10.4,"created":"1624446320173"}
我想获取基于的记录month and day
,为此,我编写了如下查询
db.collection.aggregate([
{ "$group": {
_id: { month:{ "$month": { "$toDate": "$created" }, day: "$day" } },
product: { "$push": "$name" }
}}
])
但它给出了错误
An object representing an expression must have exactly one field: { $month: { $toDate: \"$created\" }, day: \"$day\" }
预期产出
{
month:5
day:12
products:[
{
"name" : "Phone Service Family Plan"
},
{"name" : "Phone Service Core Plan"}
]
}
解决方案
您需要首先使用 $toLong 将字符串转换为 long并使用$dayOfMonth运算符,因为$day
MongoDB 中没有:
db.collection.aggregate([
{
"$group": {
_id: {
month: { "$month": { "$toDate": { $toLong: "$created" } } },
day: { "$dayOfMonth": { "$toDate": { $toLong: "$created" } } }
},
product: {
"$push": "$name"
}
}
},
{
$group: {
_id: "$_id.month",
monthDays: {
$push: {
day: "$_id.day",
product: "$product"
}
}
}
},
{
$project: {
_id: 0,
month: "$_id",
monthDays: 1
}
},
])
推荐阅读
- php - PHP 命令和我的文件系统不起作用
- python - 使用热阴影和文本值过滤 altair 热图
- java - Java parse data from html table with jsoup
- javascript - Angular constructor doesn't set a local variable before ngOnInit() is called
- c# - Autofac: Registering nested generic Interfaces and classes
- acumatica - Pass data to new record when creating via "Add New" in Selector in Acumatica
- sockets - Python simple UDP server does not receive message with IP options
- javascript - how to get the input value into the controller w/o using angular?
- asp.net-mvc - 如何激活课程?
- c++ - GCC/G++ different attitudes for: void* to int