首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MongoDB聚合框架

MongoDB聚合框架
EN

Stack Overflow用户
提问于 2013-07-14 21:06:16
回答 1查看 353关注 0票数 0

我有一个文档,它的结构如下:

代码语言:javascript
复制
{
  '_id' => 'Star Wars',
  'count' => 1234,
  'spelling' => [ ( 'Star wars' => 10, 'Star Wars' => 15, 'sTaR WaRs' => 5) ]
}

我希望获得前N个文档(按降序计数),但每个文档只有一个拼写(值最高的那个)。有没有办法用聚合框架做到这一点?

我可以很容易地获得前10个结果(使用$sort和$limit)。但是我怎么才能让每个人只有一个拼写呢?

例如,如果我有以下三条记录:

代码语言:javascript
复制
{
  '_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) ]
}

我问前两个结果,我会得到:

代码语言:javascript
复制
{
  '_id' => 'willow',
  'count' => 2211,
  'spelling' => 'Willow'
}
{
  '_id' => 'star_wars',
  'count' => 1234,
  'spelling' => 'Star Wars'
}

(或者类似的东西)

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-14 22:53:38

按照设计,您的模式将使使用除MapReduce以外的任何东西变得困难,因为您已经将对象的键用作值。因此,我调整了您的模式以更好地匹配MongoDB的功能(在本例中也是以JSON格式):

代码语言:javascript
复制
{
  '_id' : 'star_wars',
  'count' : 1234,
  'spellings' : [ 
    { spelling: 'Star wars', total: 10}, 
    { spelling: 'Star Wars', total : 15}, 
    { spelling: 'sTaR WaRs', total : 5} ]
}

注意,它现在是一个对象数组,具有特定的键名、spellingtotal的值(我不知道这个数字实际表示什么,所以在我的示例中我将其称为total )。

关于聚合:

代码语言:javascript
复制
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' }
        }
    }
])

  1. 展开所有数据,以便聚合管道可以访问数组的各种值
  2. 扁平化数据以包括管道所需的关键方面。在本例中,是特定的spellingtotalcount。对组进行
  3. 排序,这样最后一个分组可以使用$first
  4. Then,组,这样只返回每个_id$first值,然后还返回count,由于它在管道中展平的方式,每个临时文档都将包含count字段。

结果:

代码语言:javascript
复制
[
{
    "_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"
}
]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17639651

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档