我对mongodb很新,所以请原谅我的遗忘。 我的数据库样本如下:
{
"_id" : ObjectId("58db82583d5b9f0a47c3db6f"),
"People" : [
"Ivar Zapp"
],
"Link" : [
"https://wikileaks.org/gifiles/docs/19/1971280_panama-costa-rica-cuba-111104-.html"
]
}
{
"_id" : ObjectId("58db82583d5b9f0a47c3db70"),
"People" : [
"Ivar Zapp"
],
"Link" : [
"https://wikileaks.org/gifiles/docs/87/872609_panama-costa-rica-cuba-111104-.html"
]
}
{
"_id" : ObjectId("58db82583d5b9f0a47c3db71"),
"People" : [
"Ivar Zapp"
],
"Link" : [
"https://wikileaks.org/gifiles/docs/19/1964024_-latam-centam-brief-111104-.html"
]
}
现在我的问题是,根据上面的代码片段,我如何获得与某个人姓名相关的链接数?以下示例输出:
{
"People" : "Ivar Zapp",
"link_Count" : "3"
}
我考虑过聚合,但我现在似乎无法找到使用聚合的解决方案。我愿意接受任何解决方案或反馈,只要它能帮助我进步一点点。提供任何解决方案或反馈非常感谢!提前谢谢!
答案 0 :(得分:2)
您需要使用$ group操作: 您尝试以下命令,
db.collection.aggregate([
{ $group: {
_id: '$People',
count: { $sum: 1 }
}},
{ $project: {
_id: 0,
People: '$_id',
count: 1
}}
]);
输出:
{
"count": 3,
"People": ["Ivar Zapp"]
}