mongodb 分组每组前几个

具体见注释,如有不明白,可评论,可私信,可微信。
例子如下:
数据

{"_id":"1", "name":"A", "category":"分类1", "active":1, "createdate":"2021-11-10T09:00:08.170Z"},
{"_id":"2", "name":"B", "category":"分类1","active":1, "createdate":"2021-11-10T08:58:31.442Z"},
{"_id":"3", "name":"C", "category":"分类1", "active":1, "createdate":"2021-11-10T08:57:31.543Z"},
{"_id":"4", "name":"D", "category":"分类2", "active":2, "createdate":"2021-11-10T08:44:12.140Z"},
{"_id":"5", "name":"E", "category":"分类2", "active":1, "createdate":"2021-11-10T08:43:22.434Z"},
{"_id":"6", "name":"F", "category":"分类2", "active":1, "createdate":"2021-11-10T07:52:44.067Z"},
{"_id":"7", "name":"G", "category":"分类2", "active":1, "createdate":"2021-11-10T07:51:42.293Z"},

拿到每个分类的前两条数据

db..aggregate([
            {$match: {active: 1,}},//匹配active为1的数据
            { "$sort": { "createdate": -1 } },//根据时间排序
            {$group:{_id:"$category",items:{$push:"$$CURRENT"}}},//根据分类,找到分类下的数据列表$$CURRENT也可$$ROOT
            { "$project": {
                    "items": {"$slice": [ "$items", 2 ] }//每组数据有3条
            }},
            {
                "$project": {
                    "items._id": 0,
                }
            },//去掉不必要的字段
            { "$sort": { "_id": -1 } },//再根据分类排序,上面把分类赋予了_id,所以此处是_id排序

        ])

输出结果

[
        {
            "_id":"分类1",
            "items":[
                           { "name":"A", "category":"分类1", "active":1, "createdate":"2021-11-10T09:00:08.170Z"},
                           {"name":"B", "category":"分类1","active":1, "createdate":"2021-11-10T08:58:31.442Z"},

                     ]
        },
        {
            "_id":"分类2",
            "items":[
                        { "name":"E", "category":"分类2", "active":1, "createdate":"2021-11-10T08:43:22.434Z"},
                        {"name":"F", "category":"分类2", "active":1, "createdate":"2021-11-10T07:52:44.067Z"},
                    ]
        }
    ]
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小~小

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值