我正在尝试根据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个。
1条答案
按热度按时间dojqjjoe1#
会是这样一个:
Mongo Playground