I need to match all models where array has objects where the field is only equal to 0

There is the model example.

{
            "_id": "5b841bc3e7179a43f9ad53a8",
            "title": "Lunar",
            "brand": "Nike",
            "sizes": [
                {
                    "sizeValue": 36,
                    "count": 8,
                    "_id": "5fa595b97cc8a20ca00493e2"
                },
                {
                    "sizeValue": 49,
                    "count": 7,
                    "_id": "5fa595b97cc8a20ca00493e3"
                },
                {
                    "sizeValue": 44,
                    "count": 0,
                    "_id": "620927644fe2a131b1477842"
                }
            ],
            "sex": "жіночі"
        }

As you see, there is sizes array in which objects have the count field. Hence, I need to match all models where only all count field is equal to 0 or sizes array is empty.

I tried using this query but this did not work.

find({sizes:  {$all: {$elemMatch: {count:{$eq: 0}}}};});

The estimated result must be as following:

[    
        {
            "_id": "61dca3a72cdd6222592e8ba6",
            "title": "643 Ultra",
            "brand": "New Balance",
            "sizes": [],
            "sex": "чоловічі"
        },
        {
            "_id": "61fabd7d9e38f5770f4f52e5",
            "title": "568",
            "brand": "New Balance",
            "sizes": [ 
                   {
                    "_id": "62c0b68987bfb4c96d096c76",
                    "sizeValue": 39,
                    "count": 0
                 }
             ],
            "sex": "жіночі"
        },
        {
            "_id": "61ffdfc839180210ea77a407",
            "title": "Чорні в'єтнамки",
            "brand": "Adidas",
            "sizes": [
                {
                    "_id": "62c0b68987bfb4c96d096c76",
                    "sizeValue": 40,
                    "count": 0
                }
            ],
            "sex": "чоловічі"
        }
]

The simple query

{ "sizes.count" : 0 }

will matches all documents that have one element of the array sizes with the field count 0.

Then to only get the elements of sizes with count 0, you need to do a projection with $filter.

1 Like

After few attempts I find out a optimal solution.

find({
         $or:[
            {sizes: {
                 $not: {
                         $elemMatch:  {
                                   count: {$ne: 0}}
                         }}},
            {
                sizes: {
                    $exists: true,
                    $size: 0
                }
            }]
});
1 Like

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