【问题标题】:how to aggregate in mongoDB? [duplicate]如何在 mongoDB 中聚合? [复制]
【发布时间】:2016-08-05 05:45:18
【问题描述】:

我在 json 中有一个书单如下:

{
    "_id" : ObjectId("1"),
    "author" : [
        "Mary",
        "Tony"
    ],
    "booktitle" : "Book1",
    "Category" : "Children"
}
{
        "_id" : ObjectId("2"),
        "author" : [
            "Joe",
            "Tony"
        ],
        "booktitle" : "Book2",
        "Category" : "Children"
}
{
            "_id" : ObjectId("3"),
            "author" : [
                "Joe",
            ],
            "booktitle" : "Book3",
            "Category" : "comedy"
}
.......

希望出书的前10位作者属于“儿童”。因为有些书不只是一个作者写的。我不知道该怎么做。

鉴于上面的示例,book1 和 book2 属于“儿童”,Tony 写了 2 本书,Mary 和 Joe 写了 1 本书。因此,前 3 名作家的顺序是 Tony、Mary、Joe。

我只是写下:

db.table.find({Category: "Children"}).aggregate({$group:{_id: '', count : {$sum : 1}}}, {$sort: {count : -1}})

但不知道如何编写组部分。谢谢。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    tl;博士

    其实很简单。

    db.books.aggregate([
        { $match:{ Category:"Children" }},
        { $project:{ _id:0, author:1 }},
        { $unwind:"$author" },
        { $group:{ _id:"$author", count:{ $sum: 1} }},
        { $sort:{ count:-1 }},
        { $limit: 10 } 
    ])
    

    详细说明

    样本数据

    { "_id" : ObjectId("570ec0a29307105e18d42bae"), "author" : [ "Mary", "Tony" ], "booktitle" : "Book1", "Category" : "Children" }
    { "_id" : ObjectId("570ec0cf9307105e18d42baf"), "author" : [ "Joe", "Tony" ], "booktitle" : "Book2", "Category" : "Children" }
    { "_id" : ObjectId("570ec0f59307105e18d42bb0"), "author" : [ "Joe" ], "booktitle" : "Book3", "Category" : "comedy" }
    

    聚合解释

    1. { $match:{ Category:"Children" }} 首先,我们找到相关类别中的所有书籍
    2. { $project:{ _id:0, author:1 }} 我们只需要author 数组,我们
    3. { $unwind:"$author" }。这意味着我们为每个数组元素创建一个新文档,该文档保留原始文档的其他字段。在我们的例子中,这是 none,因此,在这个阶段,我们的聚合结果如下所示:

      { "author" : "Mary" }
      { "author" : "Tony" }
      { "author" : "Joe" }
      { "author" : "Tony" }
      
    4. { $group:{ _id:"$author", count:{ $sum: 1} }} 接下来,我们只需按作者分组,并为每次出现相同的不同作者姓名增加一个计数器。
    5. { $sort:{ count:-1 }}我们按照刚刚创建的字段count降序排列,
    6. { $limit: 10 } 限制在数量最多的十位作者

    聚合给出以下内容

    结果

    { "_id" : "Tony", "count" : 2 }
    { "_id" : "Joe", "count" : 1 }
    { "_id" : "Mary", "count" : 1 }
    

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2019-09-29
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      相关资源
      最近更新 更多