mongodb - MongoDB 聚合 + $match + $group + 数组
问题描述
这是我的 MongoDB 查询:
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 收藏:
"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
}
]
}
如您所见,channels 是一个数组,“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}}
])
推荐阅读
- java - 平台无关语言的真正含义是什么?
- javascript - 添加闪耀动画在特殊情况下不起作用
- ios - 协调器的 RxSwift 并发问题
- javascript - 为什么 React 没有渲染我的地图功能?
- assembly - 将计算出两个字母在字母表中的距离
- firebase-storage - 使用图片 URL 链接获取 storageReference
- swift - 连接到 Cloud SQL 时,Cloud Run 上的 Vapor 应用程序抛出异常
- swift - 使用 Xcode 和 Swift 中的 MapKit 注释理解视图控制器 segues
- node.js - 如何检查 Google Client_ID 和 Client_Secret 是否有效
- c# - 使用 c# mvc 以编程方式安排微软团队会议