CaffeinateOften
CaffeinateOften

Reputation: 571

How to flatten nested arrays and remove empty arrays only if they are nested using MongoDB aggregation framework?

I'm trying to transform my documents as shown below. I've tried using the $unwind operator, then the $group operator combined with the $push operator to re-build the $user_mentions array, but this also pushes all of the empty arrays and I'm back to square one again.

What I start with:

{
  _id: "6222407",
  name: "Chris",
  user_mentions: [
    [],
    [{_id:"963222", name: "Bob"}, {_id:"234324", name: "Fred"}]
  ]
},
{
  _id: "34566",
  name: "Tim",
  user_mentions: [
    []
  ]
},
{
  _id: "65343",
  name: "Sean",
  user_mentions: [
    [],
    []
  ]
}
}

What I want:

{
  _id: "6222407",
  name: "Chris",
  user_mentions: [
    {_id:"963222", name: "Bob"}, 
    {_id:"234324", name: "Fred"}]
  ]
},
{
  _id: "34566",
  name: "Tim",
  user_mentions: [

  ]
},
{
  _id: "65343",
  name: "Sean",
  user_mentions: [

  ]
}

Upvotes: 1

Views: 3533

Answers (1)

HoefMeistert
HoefMeistert

Reputation: 1200

Because of the nature of your document layout you have to unwind twice (array in array). Also use the preserveNullAndEmptyArrays on the second unwind to keep empty array's in the documents.

Here's the aggregation:

db.collection.aggregate(
  [
    {
      $unwind: "$user_mentions"
    },
    {
      $unwind: { path: "$user_mentions", preserveNullAndEmptyArrays: true }
    },
    {
      $group: {
      _id : "$_id",
      name : {$first : "$name"},
      user_mentions : { $push : "$user_mentions"}
      }
    }
  ]    
);

Upvotes: 3

Related Questions