Search code examples
mongodbaggregation-framework

MongoDB - How to remove nested arrays with only one element


I want to remove the arrays containing only one object and keep the arrays with more than one objects in the following example:

[
  {
    "_id": "102",
    "yearDiff": [
      [
        {
          "e_date": ISODate("2016-04-01T00:00:00Z"),
          "h_val": 4,
          "p_id": "102"
        }
      ],
      [
        {
          "e_date": ISODate("2016-04-01T00:00:00Z"),
          "h_val": 5,
          "p_id": "102"
        }
      ],
      [
        {
          "e_date": ISODate("2018-04-01T00:00:00Z"),
          "h_val": 6,
          "p_id": "102"
        },
        {
          "d_val": 62,
          "e_date_1": ISODate("2004-09-01T00:00:00Z"),
          "p_id": "102",
          "s_val": 81
        },
        {
          "d_val": 62,
          "e_date_1": ISODate("2005-09-01T00:00:00Z"),
          "p_id": "102",
          "s_val": 81
        }
      ]
    ]
  }
]

I want to only keep:

[
            {
              "e_date": ISODate("2018-04-01T00:00:00Z"),
              "h_val": 6,
              "p_id": "102"
            },
            {
              "d_val": 62,
              "e_date_1": ISODate("2004-09-01T00:00:00Z"),
              "p_id": "102",
              "s_val": 81
            },
            {
              "d_val": 62,
              "e_date_1": ISODate("2005-09-01T00:00:00Z"),
              "p_id": "102",
              "s_val": 81
            }
          ]

and pull out the first two arrays.

I have tried to check for the second elements in each array and if it is not there then remove it by: {"yearDiff.0.1.p_id":{$exists:true}} But it is not working. Here is the playground https://mongoplayground.net/p/AzLrMisIP3k


Solution

  • Query

    • you can $filter and keep only those that have $size $ne to 1

    Playmongo

    aggregate(
    [{"$set": 
       {"yearDiff": 
         {"$filter": 
           {"input": "$yearDiff", "cond": {"$ne": [{"$size": "$$this"}, 1]}}}}}])