[英]How to paginate aggregation query results in MongoDB and get a total document count (Node.js + Mongoose)?
[英]mongodb aggregation get the total number of matched document
我有以下示例文檔保存在mongogb中,例如:
{
name: 'andy',
age: 19,
description: 'aaa aaa aaa'
}
{
name: 'andy',
age: 17,
description: 'bbb bbb bbb'
}
{
name: 'leo',
age: 10,
description: 'aaa aaa aaa'
}
{
name: 'andy',
age: 17,
description: 'ccc ccc ccc'
}
要獲得每個匹配集中的名稱總數,管道應該是什么樣子? 因此我可以將此總和編號用於下一個管道。 我目前擁有的管道是這樣的:
var pip = [
{
$match: { name: 'andy' }
}
]
我想得到這樣的結果
{
name: 'andy',
age: 19,
description: 'aaa aaa aaa',
total_andy: 3
}
{
name: 'andy',
age: 17,
description: 'bbb bbb bbb',
total_andy: 3
}
{
name: 'andy',
age: 17,
description: 'ccc ccc ccc',
total_andy: 3
}
我不清楚你想要什么。 而且我沒有足夠的聲譽在評論中要求這樣做。 因此,讓我嘗試一下。 如果答案不是您想要的,請進一步說明問題,我們將繼續進行...
var term1group = {$group :
{'_id' : '$name'},
'total_names' : {$sum : 1},
'ageAndDescription' : {$addToSet : {'$age', '$description'}}
}
var term2unwind = {$unwind : '$ageAndDescription'}
var term3project = {$project : {
_id : 0,
'name' : '_id',
'age' : '$ageAndDescription.age',
'description' : '$ageAndDescription.description',
'total_name' : 1
}
db.collection.aggregate(term1group, term2unwind, term3project);
還沒有測試過,但我希望它能起作用。
您只需要使用$group
和$sum
進行簡單計數即可。 輸出不會完全匹配,但是您可以使用NodeJS輕松重新格式化。
您顯然想對顯示的三個字段( name
, age
和description
)進行分組。 為此,只需添加字段和字段引用(使用$
):
{ $match: { name: 'andy' } },
{ $group: {
_id: { name: "$name", age: "$age", description: "$description"},
count: { $sum: 1}
}
}
要添加每個組的計數,請添加$sum
1
(對於與該組匹配的每個文檔)。
您的輸出將類似於:
{ "_id" : { "name" : "andy", "age" : 17, "description" : "ccc ccc ccc" }, "count" : 1 }
{ "_id" : { "name" : "andy", "age" : 17, "description" : "bbb bbb bbb" }, "count" : 1 }
{ "_id" : { "name" : "andy", "age" : 19, "description" : "aaa aaa aaa" }, "count" : 3 }
如果您將投影與$project
,則還可以設置輸出格式,使其與原始請求更加匹配:
{ $match: {name: 'andy' }},
{ $group: { _id: { name: "$name", age: "$age", description: "$description"} ,
count: {$sum: 1}}
},
{ $project : { name: "$_id.name", _id: 0, age: "$_id.age",
description: "$_id.description", total_andy: "$count"
}
}
結果:
{ "name" : "andy", "age" : 17, "description" : "ccc ccc ccc", "total_andy" : 1 }
{ "name" : "andy", "age" : 17, "description" : "bbb bbb bbb", "total_andy" : 1 }
{ "name" : "andy", "age" : 19, "description" : "aaa aaa aaa", "total_andy" : 3 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.