我被困在这上面已经5天了。
我试图聚合如下所示的MongoDB对象数组:
[
{
_id: 2,
store: "Vincenzo Pizza Tavern",
bundle: "",
group: "",
state: "nothing",
},
{
_id: 2,
store: "Vincenzo Pizza Tavern",
bundle: "VinnyBundle",
group: "VinnyGroup",
state: "waiting",
},
{
_id: 4,
store: "Marios",
bundle: "",
group: "Mario Group",
state: "nothing",
},
{
_id: 4,
store: "Marios",
bundle: "Mias_Dias",
group: "Mario Group",
state: "waiting",
},
{
_id: 5,
store: "Marios",
bundle: "Mias_Dias_Menu",
group: "Mario Group",
state: "current",
}
]必须在_id上对数据进行分组,并对状态字段进行排序。优先顺序是“无”、“等待”和“当前”。
Outcome:
[
{
_id: 2,
store: "Vincenzo Pizza Tavern",
bundle: "VinnyBundle",
group: "VinnyGroup",
state: "waiting",
},
{
_id: 5,
store: "Marios",
bundle: "Mias_Dias_Menu",
group: "Mario Group",
state: "current",
}
]发布于 2020-09-01 07:35:02
必须在_id上对数据进行分组,并对状态字段进行排序。优先顺序是“无”、“等待”和“当前”。
正如评论中指出的那样
_id必须是唯一的实现您在声明中提到的所需内容
db.collection.aggregate([
{
$addFields: { //custom sort order
type: {
$cond: [
{
$eq: [
"$state",
"nothing"
]
},
0,
{
$cond: [
{
$eq: [
"$state",
"waiting"
]
},
1,
2
]
}
]
}
}
},
{
$sort: {//sort
"type": 1
}
},
{
$group: {//group by `id` - a custom field than `_id`
"_id": "$id",
"data": {
$push: "$$ROOT"
}
}
}
])https://stackoverflow.com/questions/63683110
复制相似问题