mongodb 如何查询:当月支付过1次,其他月份没有支付过的用户数量?

{"_id":"14139e126137625f0a8b0a4c3302e3f1","ordertimes":2,"mobile":"11111111111","month":"2021-09"}
{"_id":"14139e126137625f0a8b0a4d0bfdd883","ordertimes":1,"mobile":"11111111111","month":"2021-08"}
{"_id":"14139e126137625f0a8b0a4e4d80ff30","ordertimes":4,"mobile":"11111111111","month":"2021-07"}
{"_id":"14139e126137625f0a8b0a4f134e77c9","ordertimes":7,"mobile":"11111111111","month":"2021-06"}
{"_id":"14139e126137625f0a8b0a4c3302e3f2","ordertimes":1,"mobile":"22222222222","month":"2021-09"}
{"_id":"14139e126137625f0a8b0a4d0bfdd884","ordertimes":0,"mobile":"22222222222","month":"2021-08"}
{"_id":"14139e126137625f0a8b0a4e4d80ff36","ordertimes":0,"mobile":"22222222222","month":"2021-07"}
{"_id":"14139e126137625f0a8b0a4f134e77c8","ordertimes":0,"mobile":"22222222222","month":"2021-06"}

上面这个表:表示用户(手机号)在每个月的支付订单数量,即

{"_id":"14139e126137625f0a8b0a4c3302e3f1","ordertimes":2,"mobile":"11111111111","month":"2021-09"}

表示,手机用户11111111111在2021-09月份,订单数量为2。

想要查询:

当月(2021-09)支付过1次(ordertimes=1),其他月份没有支付过(ordertimes=0)的用户数量。

 

在 MongoDB 中,可以使用以下查询语句实现上述需求:

db.collection.aggregate([
    {
        $match: {
            $expr: {
                $and: [
                    { $eq: [ "$month", "2021-09" ] },
                    { $eq: [ "$ordertimes", 1 ] }
                ]
            }
        }
    },
    {
        $group: {
            _id: "$mobile",
            ordertimes: { $sum: "$ordertimes" }
        }
    },
    {
        $match: {
            $expr: {
                $eq: [
                    {
                        $sum: {
                            $map: {
                                input: "$ordertimes",
                                as: "o",
                                in: {
                                    $cond: [
                                        { $eq: [ "$$o", 0 ] },
                                        1,
                                        0
                                    ]
                                }
                            }
                        }
                    },
                    0
                ]
            }
        }
    },
    {
        $group: {
            _id: null,
            count: { $sum: 1 }
        }
    }
])

上述代码会先通过 $match 操作筛选出当月(2021-09)支付过1次(ordertimes=1)的记录,再通过 $group 操作以手机号为键分组统计每个用户的订单数量。最后,再通过另一个 $match 操作筛选出其他月份(除了2021-09)没有支付过(ordertimes=0)的用户。最后一步 $group 操作,将所有用户数量累加起来,即得到符合条件的用户数量。