根据子文档的得分对mongo集合进行排序 [英] sort mongo collection based on the score of child documents

查看:106
本文介绍了根据子文档的得分对mongo集合进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个收藏集,编辑和书籍。每本书都与编辑者的parentId字段相关联,每本书都有一个得分(例如1、2、3)和类型(科幻,浪漫等)。

I've two collections, editors and books. Each book is associated with a parentId field to an editor and each book is has a score ( say 1, 2, 3 ) and a type ( sci-fi, romance, etc ...) .

编辑者:

{ _id: 1, name: "editor1" }
{ _id: 2, name: "editor2" }
...

和书籍

{ _id: 1, name: "book1", score: 1, parentId: 1, type: "sci-fi" }
{ _id: 2, name: "book2", score: 3, parentId: 1, type: "romance" }

{ _id: n, name: "bookn", score: 1, parentId: m, type: "detective" }

我想编写一个聚合,将

因此,我可以检索出前十名科幻小说中编辑次数最多的编辑者热门书籍,或不分类别,仅是最受欢迎书籍的前10名编辑者。

So i can retrieve the first 10 editors of sci-fi with the most popular books, or just the first 10 editors with the most popular books regardless of categories.

抓住了吗?使用mongo 3.2。我给人留下深刻的印象,即3.4和3.6可以实现这一点(我很想看看如何做到),但是目前,我要运送的产品是mongo 3.2,我无法更改它……

The catch ? Using mongo 3.2 . I've the strong impression that this is possible with 3.4 and 3.6 (And I'd love to see how), but at the moment, the product I'm shipping is with mongo 3.2 and I can't change that ...

在编辑器集合上进行汇总,我尝试首先查找所有编辑器的书籍,然后展开,按parentId分组并用总和创建新的字段分数类别中所有书籍的分数,但后来我被困在尝试使用此分数将其与编辑者相关联,最后对结果进行排序。

Aggregating on the editors collection, I've tried to first lookup all the books for an editor, then unwind, group by parentId and create a new field score with the sum of the score of all books in this group, but then I'm stuck trying to use this score to associate it to the editors and finally sort the result.

我正在流星订阅中使用此聚合。

I'm using this aggregation in a meteor subscription.

推荐答案

您可以尝试下面的汇总。

You can try below aggregation.


因此,我可以用最受欢迎的
书籍检索科幻小说的前10名编辑

So i can retrieve the first 10 editors of sci-fi with the most popular books



db.editors.aggregate([
  {"$lookup":{
    "from":"books",
    "localField":"_id",
    "foreignField":"parentId",
    "as":"books"
  }},
  {"$unwind":"$books"},
  {"$match":{"books.type":"sci-fi"}},
  {"$group":{
    "_id":"$_id",
    "name":{"$first":"$name"},
    "scores":{"$sum":"$books.score"}
  }},
  {"$sort":{"scores":-1}},
  {"$limit":10}
])




或仅前10名编辑者



db.editors.aggregate([
  {"$lookup":{
    "from":"books",
    "localField":"_id",
    "foreignField":"parentId",
    "as":"books"
  }},
  {"$project":{
    "name":1,
    "scores":{"$sum":"$books.score"}
  }},
  {"$sort":{"scores":-1}}
])

这篇关于根据子文档的得分对mongo集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆