【发布时间】:2016-03-20 15:03:57
【问题描述】:
我正在尝试获取我的 MongoDB 集合中的所有文档
- 按不同的客户 ID (custID)
- 其中状态码 == 200
- 分页(跳过和限制)
- 返回指定字段
var Order = mongoose.model('Order', orderSchema());
我最初的想法是使用mongoose db query,但是你不能使用distinct和skip and limit作为Distinct is a method that returns an "array", and therefore you cannot modify something that is not a "Cursor":
Order
.distinct('request.headers.custID')
.where('response.status.code').equals(200)
.limit(limit)
.skip(skip)
.exec(function (err, orders) {
callback({
data: orders
});
});
然后我想使用Aggregate,使用$group 来获取不同的customerID 记录,$match 返回所有具有状态代码200 的唯一customerID 记录,并使用$project 来包含我想要的字段:
Order.aggregate(
[
{
"$project" :
{
'request.headers.custID' : 1,
//other fields to include
}
},
{
"$match" :
{
"response.status.code" : 200
}
},
{
"$group": {
"_id": "$request.headers.custID"
}
},
{
"$skip": skip
},
{
"$limit": limit
}
],
function (err, order) {}
);
这会返回一个空数组。如果我删除project,实际上我需要更多时,只会返回$request.headers.custID 字段。
有什么想法吗?
【问题讨论】:
标签: mongodb mongoose pagination mongodb-query aggregation-framework