我的查询:
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,那么第一个记录有时是冷的,有时是热的。我也尝试添加stage $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 }
}
])
我的期望是结果返回相同的顺序
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'
}
},
{
$sort: { type: 1 }
},
{
$skip: skip,
},
{
$limit: limit + skip,
}
])
我改变了sort
,limit
,skip
的顺序