我有下表: -
id order_number product_number order_status schedule_datetime
1 001 001.1 SUCCESS 20180103
2 001 001.2 SUCCESS 20180102
3 111 111.1 SUCCESS 20171225
4 111 111.2 SUCCESS 20171224
5 222 222.1 INPROGRESS 20171122
6 222 222.2 ON_HOLD 20171121
7 222 222.3 PARTLY_SUCCESS 20171121
我在这里尝试的是,如果任何product_number与查询中给出的状态匹配,它应该显示order_numbers的年份和列表。
输入1:order_status = SUCCESS,输出低于
{
"order_statuses" : [
"SUCCESS"
],
"year" : "2018",
"order_number" : "001"
},
{
"order_statuses" : [
"SUCCESS"
],
"year" : "2017",
"order_number" : "111"
}
输入2:order_status = PARTLY_SUCCESS,输出下面应该
{
"order_statuses" : [
"PARTLY_SUCCESS",
"ON_HOLD",
"INPROGRESS"
],
"year" : "2017",
"order_number" : "222"
} 在此链接convert mysql query contains sum and group_concat to mongodb query的帮助下,我试图获得所需的结果,但在查询下方给出错误“字段名称'$ addFields'不能是运算符名称”。因为我不想显示计数我尝试添加到单独的组,但它没有帮助。
db.order_summary.aggregate([
{"$project":{
"schedule_datetime":1,
"order_number ":1,
"order_status":{"$ifNull":["$order_status",""]}
}},
{"$group":{
"_id":{
"order_number ":"$order_number ",
"order_status":"$order_status"
},
"study_date":{"$first": "$study_date"}
}},
{"$sort":{"_id.order_status": 1}},
{"$group":{
"_id":{
"order_number ":"$_id.order_number "
},
"study_date":{"$first": "$study_date"},
"order_status":{"$push": "$_id.order_status"}
}},
{"$group":{
"_id":{
"$substr":["$study_date",0,4]
},
"count":{
"$sum":{
"$cond": [
{"$in": ["$order_status",[["SUCCESS"],["INPROGRESS","SUCCESS"]]]},
1,0
]
}
},
"order_numbers":{"$push":"$_id.order_number "},
"$addFields":{"$size":"$order_numbers"},
}},
{"$match":{"order_numbers":{"$gt":0}}},
{"$sort":{"_id":-1}}
])
请按照上面的输出帮助显示年份和order_numbers列表,谢谢!
答案 0 :(得分:0)
您可以尝试以下聚合查询。
首先$group
获取不同的订单号和状态组合,然后选择最新的时间戳。
第二个$group
按年份和状态进行分组,然后选择所有订单号。
$match
将状态组与输入状态进行比较。
db.order_summary.aggregate([
{"$project":{
"schedule_datetime":1,
"order_number ":1,
"order_status":{"$ifNull":["$order_status",""]
}
}},
{"$sort":{"schedule_datetime":-1}},
{"$group":{
"_id":{
"order_number":"$order_number",
"order_status":"$order_status"
},
"schedule_datetime":{"$first":"$schedule_datetime"}
}},
{"$group":{
"_id":{
"year":{"$substr":["$schedule_datetime",0,4]},
"order_number":"$_id.order_number"
},
"order_statuses":{"$push":"$_id.order_status"}
}},
{"$redact": {"$cond":[{"$in": ["SUCCESS","$order_statuses"]},"$$KEEP","$$PRUNE"]}},
{"$sort":{"_id.year":-1}},
{"$project":{"_id":0, "year":"$_id.year","order_number":"$_id.order_number", "order_statuses":1 }},
])