我在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
}
答案 0 :(得分:1)
我不清楚你想要什么。而且我没有足够的声誉在评论中提出要求。让我有机会回答。如果答案不是你想要的,那就进一步澄清问题,我们就会明白......
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);
没有经过测试,但我希望这会有效。
答案 1 :(得分:0)
您只需使用$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 }