【发布时间】:2021-11-05 02:50:09
【问题描述】:
这是我的查询:
db.getCollection('alerts').aggregate([{
$match: {
houseId: ObjectId("609100a56ed9f8001351aee3")
}
}, {
$group: {
_id: '$type',
alerts: {
$push: {
_id: '$_id',
type: '$type'
}
}
}
},
{
$project: {
_id: false,
type: '$_id.type',
alerts: '$alerts'
}
}
])
结果:
[{
"type" : "cool",
"alerts" : [
{
"_id" : ObjectId("61387e740dc3d853f1eee5b0"),
"type" : "cool"
}
]
}, {
"type" : "hot",
"alerts" : [
{
"_id" : ObjectId("61387e740dc3d853f1eee5b0"),
"type" : "hot"
},
{
"_id" : ObjectId("61387e740dc3d853f1eee5b0"),
"type" : "hot"
}
]
}]
但有时它也会返回:
[{
"type" : "hot",
"alerts" : [
{
"_id" : ObjectId("61387e740dc3d853f1eee5b0"),
"type" : "hot"
},
{
"_id" : ObjectId("61387e740dc3d853f1eee5b0"),
"type" : "hot"
}
]
}, {
"type" : "cool",
"alerts" : [
{
"_id" : ObjectId("61387e740dc3d853f1eee5b0"),
"type" : "cool"
}
]
}]
我为分页添加了一个阶段 $limit 和 $skip,如果 skip: 0, limit: 1 那么第一条记录有时很酷,有时很热。我也尝试添加阶段 $sort 以使顺序一致,但它不起作用。
我的带有排序和限制的脚本,跳过
db.getCollection('alerts').aggregate([{
$match: {
houseId: ObjectId("609100a56ed9f8001351aee3")
}
}, {
$group: {
_id: '$type',
alerts: {
$push: {
_id: '$_id',
type: '$type'
}
}
}
},
{
$project: {
_id: false,
type: '$_id.type',
alerts: '$alerts'
}
},
{
$limit: limit + skip,
},
{
$skip: skip,
},
{
$sort: { type: 1 }
}
])
我的预期是结果返回相同的顺序
【问题讨论】:
-
你能提供排序对象吗?
-
在
$group阶段之前插入阶段{$sort: {type: 1}}。 -
@mohammadNaimi { 排序:{ 类型:1 }}
-
@WernfriedDomscheit 我在最后阶段推送它。因为我认为在限制之后,跳过结果可能会减少并且排序运算符会更快。但是排序不起作用。
-
你是否在聚合中添加了跳过和限制?