2

I'm querying a MongoDB collection to extract informations, thus only aggregation operations are possible (i.e. no update()).

From several documents shaped like these, where each contains an embedded array with at least one document with a partNum : "1200664" field):

{
    "recType" : "H1",
    "progCount" : "097314238",
    "items" : [ 
        {
            "qty" : "00011",
            "partNum" : "4471719"
        },
        {
            "qty" : "00027",
            "partNum" : "1200664"
        }
    ]
},
{
    "recType" : "H1",
    "progCount" : "175564685",
    "items" : [ 
        {
            "qty" : "00027",
            "partNum" : "1200664"
        }
    ]
}

I'm trying to get the following result, where each document maintains its shape (so no $unwind or $replaceRoot stages are allowed), but all the embedded array elements that would not satisfy a {$match: {partNum: "1200664"}} are removed:

{
    "recType" : "H1",
    "progCount" : "097314238",
    "items" : [ 
        {
            "qty" : "00027",
            "partNum" : "1200664"
        }
    ]
},
{
    "recType" : "H1",
    "progCount" : "175564685",
    "items" : [ 
        {
            "qty" : "00027",
            "partNum" : "1200664"
        }
    ]
}

I did several attemps with the $redact pipeline stage, but I can't come up with a working invocation, let alone obtain any result similar to the above.
I'm even wondering whether $redact is the correct operation here.

watery
  • 4,030
  • 5
  • 38
  • 70

1 Answers1

2

You might need to use $filter in $project stage to filter array elements. $eq used in the cond to filter all non matching array elements

{
    $project : {
        items : { $filter : { input : "$items", as : "item", cond : { $eq : ["$$item.partNum" , "1200664"] } } }
    }
}
Saravana
  • 11,085
  • 2
  • 29
  • 43