Redact on nested array values

Hello!

Having some issues understanding the $redact stage and cant seem to understand what i’m doing wrong or just missing. I’ve read the docs but it doesn’t go through my specific need. I want to redact some nested items based on a id/number in a two level deep array. If i omit the array and use a regular key/value it does work. But not when having the values in an array.

I want to redact/remove all the items (articles) where the ids don’t match the input/query id that i provide. If $redact is not bes suitable for this i will happy take other solutions, but preferably non that uses $unwind and $group.

If i have a single key/value as authorId as in this playground it does work.

But if I have multiple Ids in an array it does not work. As this

Thanks!

Sample data as it looks as i need it.

[
  {
    "title": "one title",
    "articles": [
      {
        content: "lorem ipsum",
        authorIds: [
          1
        ],
        
      },
      {
        content: "bacon ipsum",
        authorIds: [
          2,
          3,
          4
        ]
      },
      {
        content: "hippsum dippsum",
        authorIds: [
          3,
          5
        ]
      },
      {
        content: "hippsum dippsum",
        authorIds: [
          4
        ]
      }
    ],
    
  }
]

My pipeline

db.collection.aggregate([
  {
    "$project": {
      title: 1,
      articles: 1,
      articleCount: {
        $size: "$articles"
      },
      
    },
    
  },
  {
    "$redact": {
      "$cond": {
        "if": {
          "$or": [
            {
              "$eq": [
                "$authorIds",
                2 // match on this authorId
              ]
            },
            {
              $gte: [
                "$articleCount",
                1
              ]
            },
            
          ]
        },
        "then": "$$DESCEND",
        "else": "$$PRUNE"
      }
    }
  },
  
])

Solved it by using $setIntersection in the redact condition

{
    "$redact": {
      "$cond": {
        "if": {
          "$or": [
            {
              $gte: [
                "$articleCount",
                1
              ]
            },
            {
              $gt: [
                {
                  $size: {
                    $setIntersection: [
                      "$authorIds",
                      [
                        2
                      ]
                    ]
                  }
                },
                0
              ]
            }
          ]
        },
        "then": "$$DESCEND",
        "else": "$$PRUNE"
      }
    }
  }

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.