有没有一种方法可以使用聚合管道方法进行此查询 [英] Is there a way to use the aggregate pipeline method for this query

查看:93
本文介绍了有没有一种方法可以使用聚合管道方法进行此查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个在线商店中有一个针对商品的2000多个评论的数据库,我正在寻找所有至少发表5条评论的用户,并且我想列出他们的姓名,评论数量和评论者ID

I have a database of over 2000 reviews for products on an online store, and I am trying to find all of the users who have written minimum 5 reviews, and I would like to list their names, number of reviews, and reviewer ID

我知道我必须使用聚合方法来执行此操作,但是在尝试时我没有运气,因为我还是mongodb的新手

I understand that I have to use aggregate method to do this but when trying I have no luck as I am still new to mongodb

我添加了一张图片,以显示数据库中某些数据的示例

I have added a picture to show an example of some of the data in the database

一个进入数据库的示例如下;

An example of one entry into the database is as below;

{
    "_id": ObjectId("5d0b70f2d7367de7f5fa0ee1"),
    "SH_reviewerID": "A2G0LNLN79Q6HR",
    "SH_asin": "0000031887",
    "SH_reviewerName": "aj_18 \"Aj_18\"",
    "SH_helpful": [
      1,
      1
    ],
    "SH_reviewText": "This was a really good",
    "SH_overall": 4.0,
    "SH_summary": "Really Cute but rather short.",
    "SH_unixReviewTime": 1337990400,
    "SH_reviewTime": "05 26, 2012"
}

我已经尝试了好几天,但是没有运气,我认为我们需要使用$ match,$ group,$ project

I have tried to work it out for over several days but have no luck, I think we need to use $match, $group, $project

推荐答案

我想您需要运行此聚合:

I guess you need to run this aggregation:

db.review.aggregate([
  {
    $group: {
      _id: "$SH_reviewerID",
      name: {
        $first: "$SH_reviewerName"
      },
      number: {
        $sum: 1
      }
    }
  },
  {
    $match: {
      number: {
        $gte: 5
      }
    }
  },
  //Optional - Order views descendant
  {
    $sort: {
      number: -1
    }
  },
  //Optional - Change field names
  {
    $project: {
      _id: 0,
      SH_reviewerID: "$_id",
      SH_reviewerName: "$name",
      SH_reviewerViews: "$number"
    }
  }
])

MongoPlayground

这篇关于有没有一种方法可以使用聚合管道方法进行此查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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