MongoDB 聚合 + $匹配 + $组 + 数组

MongoDB aggregate + $match + $group + Array

这是我的 Mongo 数据库查询:

profiles.aggregate([{"$match":{"channels.sign_up":true}},{"$group":{"_id":"$channels.slug","user_count":{"$sum":1}}},{"$sort":{"user_count":-1}}])

这是我的代码:

$profiles = Profile::raw()->aggregate([
            [
                '$match' => [
                    'channels.sign_up' => true
                ]
            ],
            [
                '$group' => [
                    '_id' => '$channels.slug',
                    'user_count' => ['$sum' => 1]
                ]
            ],
            [
                '$sort' => [
                    "user_count" => -1
                ]
            ]
        ]);

这是我的 Mongo Collection :

"channels": [
        {
            "id": "5ae44c1c2b807b3d1c0038e5",
            "slug": "swachhata-citizen-android",
            "mac_address": "A3:72:5E:DC:0E:D1",
            "sign_up": true,
            "settings": {
                "email_notifications_preferred": true,
                "sms_notifications_preferred": true,
                "push_notifications_preferred": true
            },
            "device_token": "ff949faeca60b0f0ff949faeca60b0f0"
        },
        {
            "id": "5ae44c1c2b807b3d1c0038f3",
            "slug": "website",
            "mac_address": null,
            "device_token": null,
            "created_at": "2018-06-19 19:15:13",
            "last_login_at": "2018-06-19 19:15:13",
            "last_login_ip": "127.0.0.1",
            "last_login_user_agent": "PostmanRuntime/7.1.5"
        }
],

这是我的回复:

   {
        "data": [
            {
                "_id": [
                    "swachhata-citizen-android"
                ],
                "user_count": 1
            },
            {
                "_id": [
                    "icmyc-portal"
                ],
                "user_count": 1
            },
            {
                "_id": [
                    "swachhata-citizen-android",
                    "website",
                    "icmyc-portal"
                ],
                "user_count": 1
            }
        ]
    }

我期待的是:

{
    "data": [
        {
            "_id": [
                "swachhata-citizen-android"
            ],
            "user_count": 1
        },
        {
            "_id": [
                "icmyc-portal"
            ],
            "user_count": 1
        },
        {
            "_id": [
                "website",
            ],
            "user_count": 1
        }
    ]
}

如您所见,频道是一个数组,"sign_up" 仅适用于用户注册的数组中的一个元素,因为我们有很多应用程序,因此我们必须为用户维护多个频道。

我想知道有多少用户注册了不同的频道,但作为回应,它来自所有频道,而不是 sign_up 为真的一个频道。

计数也是错误的,因为我必须记录 "slug": "swachhata-citizen-android" 和 "sign_up": true.

需要建议:)

使用$unwind 将每个包含数组的文档转换为包含嵌套字段的文档数组。在你的例子中,像这样:

profiles.aggregate([
  {$unwind: '$channels'},
  {$match: {'channels.sign_up': true}},
  {$group: {_id: '$channels.slug', user_count: {$sum: 1}}},
  {$sort: {user_count: -1}}
])