Stephan
Stephan

Reputation: 59

mongo db aggregate returns empty string from projection

I have the following structure in the mongo db (conversations collection):

Example of the content:

[
   {
  "channel_names" :
  [
    {
      "name" : "users_58908cf4-cfdf-499b-83f9-c7a0aa36fae0"
    },
    {
      "name" : "chats_55e6dd6776ed6652f40af20c",
      "type" : "events"
    }
  ],
  "messages":[{"text":"a"},{"text":"b"},{"text":"c"}]
}
]

I would like to aggregate the data and return data as follow e.g.:

[{'id' - '55e6dd6776ed6652f40af20c' , 'message_count' : 3 }]

sorted by message_count descending

I have the following code:

{ $project : { _id : false , id : { '$cond' : [ { '$eq' : [ '$channel_names.type' , 'events' ] } , '$channel_names.name' , '' ] } , message_count : { $size : { '$ifNull' : [ '$messages' , [] ] } } } }

{ $sort : { messages : -1 } }

db.collection.aggregate(...)

my problem is that $channel_names.name always returns empty string

example of my output:

[
  {
    "id": "",
    "message_count": 0
  },
  {
    "id": "",
    "message_count": 1
  },
  {
    "id": "",
    "message_count": 5
  },
  {
    "id": "",
    "message_count": 2
  }
]

because $channel_names.name is mapped to id and $channel_names.name returns empty string - id is always an empty string

Upvotes: 1

Views: 711

Answers (1)

Poorna Subhash
Poorna Subhash

Reputation: 2128

In the document, channel_names is an array, hence you have to do unwind first. Please try following pipeline.

pipeline = [
  {
    $unwind: '$channel_names'
  },
  {
    $project: {
      _id: false,
      id: '$channel_names.name',
      message_count: {$size: '$messages'}
    }
  },
  {
    $sort: {
      message_count: -1
    }
  }
]

Upvotes: 1

Related Questions