我有一个文档,它的结构如下:
{
'_id' => 'Star Wars',
'count' => 1234,
'spelling' => [ ( 'Star wars' => 10, 'Star Wars' => 15, 'sTaR WaRs' => 5) ]
}我希望获得前N个文档(按降序计数),但每个文档只有一个拼写(值最高的那个)。有没有办法用聚合框架做到这一点?
我可以很容易地获得前10个结果(使用$sort和$limit)。但是我怎么才能让每个人只有一个拼写呢?
例如,如果我有以下三条记录:
{
'_id' => 'star_wars',
'count' => 1234,
'spelling' => [ ( 'Star wars' => 10, 'Star Wars' => 15, 'sTaR WaRs' => 5) ]
}
{
'_id' => 'willow',
'count' => 2211,
'spelling' => [ ( 'willow' => 300, 'Willow' => 550) ]
}
{
'_id' => 'indiana_jones',
'count' => 12,
'spelling' => [ ( 'indiana Jones' => 10, 'Indiana Jones' => 25, 'indiana jones' => 5) ]
}我问前两个结果,我会得到:
{
'_id' => 'willow',
'count' => 2211,
'spelling' => 'Willow'
}
{
'_id' => 'star_wars',
'count' => 1234,
'spelling' => 'Star Wars'
}(或者类似的东西)
谢谢!
发布于 2013-07-14 22:53:38
按照设计,您的模式将使使用除MapReduce以外的任何东西变得困难,因为您已经将对象的键用作值。因此,我调整了您的模式以更好地匹配MongoDB的功能(在本例中也是以JSON格式):
{
'_id' : 'star_wars',
'count' : 1234,
'spellings' : [
{ spelling: 'Star wars', total: 10},
{ spelling: 'Star Wars', total : 15},
{ spelling: 'sTaR WaRs', total : 5} ]
}注意,它现在是一个对象数组,具有特定的键名、spelling和total的值(我不知道这个数字实际表示什么,所以在我的示例中我将其称为total )。
关于聚合:
db.so.aggregate([
{ $unwind: '$spellings' },
{ $project: {
'spelling' : '$spellings.spelling',
'total': '$spellings.total',
'count': '$count'
}
},
{ $sort : { total : -1 } },
{ $group : { _id : '$_id',
count: { $first: '$count' },
largest : { $first : '$total' },
spelling : { $first: '$spelling' }
}
}
])spelling、total和count。对组进行$first_id的$first值,然后还返回count,由于它在管道中展平的方式,每个临时文档都将包含count字段。结果:
[
{
"_id" : "star_wars",
"count" : 1234,
"largest" : 15,
"spelling" : "Star Wars"
},
{
"_id" : "indiana_jones",
"count" : 12,
"largest" : 25,
"spelling" : "Indiana Jones"
},
{
"_id" : "willow",
"count" : 2211,
"largest" : 550,
"spelling" : "Willow"
}
]https://stackoverflow.com/questions/17639651
复制相似问题