基于输入的MongoDB组查询

qvtsj1bj  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(159)

我正在尝试根据postType =“buy”创建前10个产品列表。我的逻辑是对postType =“buy”进行计数,并对日志集合中的前10个产品进行排序。下面是我的示例日志集合。

[
    {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "buy",
        "product": "3",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "view",
        "product": "4",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "buy",
        "product": "2",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "view",
        "product": "2",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "share",
        "product": "3",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "buy",
        "product": "2",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "buy",
        "product": "2",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "share",
        "product": "2",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "buy",
        "product": "1",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "buy",
        "product": "1",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "viewvideo",
        "product": "1",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "viewvideo",
        "product": "2",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "viewvideo",
        "product": "3",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "buy",
        "product": "4",
    },
 {
        "_id": "633dc5b761ff04e7ae8e8c0f",
        "postType": "buy",
        "product": "5",
    }
]

我的预期输出为:

[{"product":1, "count":2},{"product":2, "count":3},{"product":3, "count":1}, 
   {"product":4, "count":1},{"product":5, "count":1}
 ]

我尝试了下面的代码,但它不起作用。

{
        $project: {
          _id: 0,
          list: { $setEquals: ["$postType", "buy"] }
        }
      }

我只插入了4个产品,但实际上是10个。

dojqjjoe

dojqjjoe1#

会是这样一个:

db.collection.aggregate([
  { $match: { postType: "buy" } }, // filter on postType = "buy"
  {
    $group: {                      // group and count
      _id: "$product",
      count: { $count: {} }
    }
  },
  {
    $project: {                   // some cosmetic
      product: "$_id",
      count: 1,
      _id: 0
    }
  }
])

Mongo Playground

相关问题