Home > front end >  MongoDB group query based on input
MongoDB group query based on input

Time:10-25

I am trying to create top 10 product list based on postType = "buy". My logic is a count postType = "buy" and sort the top 10 products from the logs collection. Here are my sample log collections.

[
    {
        "_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",
    }
]

My expected output is:

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

I tried the following code, but it is not working.

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

I just inserted 4 products but it will be 10 actually.

CodePudding user response:

Would be this one:

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

  • Related