[英]Fetching total count of matching items in paged Mongo aggregate query
我已經看到了有關SO的基本問題,但無法使其適用於我的情況。 這是我的查詢:
return Order.aggregateAsync([{
$match: { status: { $ne: 'incomplete' } }
}, {
$unwind: '$items'
}, {
$match: {... }
},
{
$limit: limit
}, {
$skip: skip
}, {
$group: {
_id: '$items._id',
product: {
$first: '$items.product'
},
qty: {
$first: '$items.qty'
},
ordered: {
$first: '$ordered'
}
}
}, {
$sort: { 'ordered': -1 }
},
])...
我如何從中返回諸如:
{
items: [array of items by page/limit],
total: total items in db that match $match
}
我試過在$ match之后添加:
{
$group: {
_id: null,
items: { $push: '$items' },
count: { $sum: 1 }
}
},
但這似乎不使用限制。
樣本數據:
[{
_id:ObjectID
status: 'incomplete'
ordered: Date,
items: [{
_id: ObjectID
qty: 100,
product: ObjectID
}, {
_id: ObjectID
qty: 10,
product: ObjectID
}]
}, {
_id:ObjectID
status: 'incomplete'
ordered: Date,
items: [{
_id: ObjectID
qty: 200,
product: ObjectID
}]
}]
我想返回所有項目,按項目分組作為分頁查詢(限制,跳過):
[{
_id: ObjectID
qty: 100,
product: ObjectID
}, {
_id: ObjectID
qty: 10,
product: ObjectID
}, {
_id: ObjectID
qty: 200,
product: ObjectID
}]
以及所有匹配的項目的總數(3)。
所以:
result = {
docs: items array above,
total: 3
您嘗試此查詢,它對您有用,它將為您提供想要的結果
db.getCollection('collectionName').aggregate([
{ $unwind: '$items'},
{
$group:
{
_id: "",
"doc": { $push: "$items" },
"total":{ $sum: 1}
}
},
{ $project : { doc : 1 , total : 1,_id:0 } }
])
輸出
{
"doc" : [
{
"_id" : 11,
"qty" : 100,
"product" : 12
},
{
"_id" : 111,
"qty" : 10,
"product" : 112
},
{
"_id" : 21,
"qty" : 100,
"product" : 22
},
{
"_id" : 211,
"qty" : 10,
"product" : 212
}
],
"total" : 4.0000000000000000
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.