How can I keep the zero length values ​​during the unwinding phase of the aggregate pipeline in Mongo?

I am writing a Mongo query using an aggregate pipeline. During aggregation, I need $unwind

one of the fields. However, I don't want to $unwind

exclude records that have zero-length arrays for that field, because I still need them further down the pipeline.

My field is named items

and it is an array of objects, each containing two values: quantity

and price

. Here is a snippet of my Mongolian request:

db.MyCollection.aggregate([
    {$match: ... },
    {$project: ... },
    // put another $project here to retain zero-length values? how to format it?
    {$project: {
            _id: "$$ROOT",
            items: {
                $ifNull: [
                    {
                        $literal: {
                            quantity: 0,
                            price: 0
                        }
                    }
                ]
            }
        }
    },
    {$unwind: "$items"},
    {$group: ... },
    {$project: ... },
    ...
]);

      

As you can see, this already handles the case where the document has no margin items

present at all, in which case it adds it and gives it an empty value to unwind.

However, documents that already have a field items

, but it is empty , are not processed . I thought I could use some combination of $cond

and $size

to explicitly check for the size of zero inside another $project

, and then replace the same literal in that case, but $if

expecting a boolean, so I'm not really sure how to format this.

+3


source to share


1 answer


Change the stage project

in the pipeline as shown below:

The stage projection

performs the following two functions:

  • If an array of elements is null

    or does not exist

    , evaluates item to the field value as []

    (empty array.)
  • Next, it checks if the size

    field just calculated is items

    0

    if it is 0

    , and then changes its value to an array with a default object.


Stage code:

db.MyCollection.aggregate([
...
{$project:{"_id":"$$ROOT",
           "items":{$cond:[
                          {$eq:[{$size:{$ifNull:["$items",[]]}},0]},
                          [{"quantity":0,"price":0}],
                          "$items"
                          ]}}},
{$unwind:"$items"},
...
])

      

+4


source







All Articles