首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >是否选择集合中的所有字段,按最低字段值排序,并按不同字段“分组”?

是否选择集合中的所有字段,按最低字段值排序,并按不同字段“分组”?
EN

Stack Overflow用户
提问于 2019-06-03 06:46:21
回答 1查看 1.1K关注 0票数 1

我有一个具有以下字段的集合scores

代码语言:javascript
复制
┬────────┬───────┬──────────┐
│ player │ score │   mode   │
┼────────┼───────┼──────────┤
│  'A'   │   7   │  'easy'  │
│  'A'   │  11   │ 'medium' │
│  'A'   │  12   │  'hard'  │
│  'B'   │   9   │  'hard'  │
│  'B'   │  10   │  'easy'  │
│  'B'   │  10   │ 'medium' │
│  'C'   │   6   │ 'medium' │
│  'C'   │   9   │  'easy'  │
│  'C'   │  13   │  'hard'  │
┴────────┴───────┴──────────┘

我想选择所有最小的分数by player,这样预期的结果将是:

代码语言:javascript
复制
┬────────┬───────┬──────────┐
│ player │ score │   mode   │
┼────────┼───────┼──────────┤
│  'A'   │   7   │  'easy'  │
│  'B'   │   9   │  'hard'  │
│  'C'   │   6   │ 'medium' │
┴────────┴───────┴──────────┘

此外,我希望保持文档的原始结构,以便将预期结果加载为mongoose对象。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-03 09:31:30

您可以使用聚合框架执行以下操作:

在player上对集合进行分组,然后使用

  1. $sort
  2. 使用$group stage对player进行分组,并将每个player上的$first条目抓取到player$first $sort上的必要输出

例如,以下是基于您的示例的集合:

代码语言:javascript
复制
> db.test.find()
{ "_id": 2, "player": "A", "score": 12, "mode": "hard" }
{ "_id": 0, "player": "A", "score": 7, "mode": "easy" }
{ "_id": 1, "player": "A", "score": 11, "mode": "medium" }
{ "_id": 3, "player": "B", "score": 9, "mode": "hard" }
{ "_id": 4, "player": "B", "score": 10, "mode": "easy" }
{ "_id": 5, "player": "B", "score": 10, "mode": "medium" }
{ "_id": 6, "player": "C", "score": 6, "mode": "medium" }
{ "_id": 7, "player": "C", "score": 9, "mode": "easy" }
{ "_id": 8, "player": "C", "score": 13, "mode": "hard" }

使用上面的工作流程进行聚合:

代码语言:javascript
复制
db.test.aggregate([

  {$sort: {player: 1, score: 1}},

  {$group: { _id: '$player', 
             player: {$first:'$player'},
             score: {$first:'$score'}, 
             mode: {$first:'$mode'} }},

  {$project: { _id: 0 }},

  {$sort: {player: 1}}

])

输出为:

代码语言:javascript
复制
{ "player": "A", "score": 7, "mode": "easy" }
{ "player": "B", "score": 9, "mode": "hard" }
{ "player": "C", "score": 6, "mode": "medium" }

如果您有大量的集合,请确保您有一个规范为{player: 1, score: 1}index

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56419499

复制
相关文章

相似问题

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