我在mongo db(对话集合)中有以下结构:
内容示例:
[
{
"channel_names" :
[
{
"name" : "users_58908cf4-cfdf-499b-83f9-c7a0aa36fae0"
},
{
"name" : "chats_55e6dd6776ed6652f40af20c",
"type" : "events"
}
],
"messages":[{"text":"a"},{"text":"b"},{"text":"c"}]
}
]
我想聚合数据并返回数据如下:
[{'id' - '55e6dd6776ed6652f40af20c' , 'message_count' : 3 }]
按message_count降序排序
我有以下代码:
{ $project : { _id : false , id : { '$cond' : [ { '$eq' : [ '$channel_names.type' , 'events' ] } , '$channel_names.name' , '' ] } , message_count : { $size : { '$ifNull' : [ '$messages' , [] ] } } } }
{ $sort : { messages : -1 } }
db.collection.aggregate(...)
我的问题是$channel_names.name
总是返回空字符串
我的输出示例:
[
{
"id": "",
"message_count": 0
},
{
"id": "",
"message_count": 1
},
{
"id": "",
"message_count": 5
},
{
"id": "",
"message_count": 2
}
]
因为$channel_names.name
映射到id而$channel_names.name
返回空字符串 - id始终是空字符串
答案 0 :(得分:1)
在文档中,channel_names是一个数组,因此您必须先解开。请尝试以下管道。
pipeline = [
{
$unwind: '$channel_names'
},
{
$project: {
_id: false,
id: '$channel_names.name',
message_count: {$size: '$messages'}
}
},
{
$sort: {
message_count: -1
}
}
]