simon
simon

Reputation: 375

how to count the size if argument value is not an array

I want to sort the data whose result.template array's length is greater then to others

for example object id 5808d700536d1a3d69f4cf57 has four element which mean it will be first result. but when there is no result object exists then it says the argument to $size must be an array, but was of type: missing. How to fix it please guide

 db={
  products: [
    {
      "_id": ObjectId("5808d700536d1a3d69f4cf51"),
      result: {
        "template": [
          "Mcd",
          "ded",
          "GCD"
        ]
      },
      dataB: true
    },
    {
      "_id": ObjectId("5808d700536d1a3d69f4cf53"),
      result: {
        "template": [
          "CCD",
          "GHG"
        ]
      }
    },
    {
      "_id": ObjectId("5808d700536d1a3d69f4cf56"),
      
    },
    {
      "_id": ObjectId("5808d700536d1a3d69f4cf57"),
      result: {
        "template": [
          "VVD",
          "SSD",
          "Fsd",
          "Xcd",
          
        ]
      }
    },
    {
      "_id": ObjectId("5808d700536d1a3d69f4cf43"),
      
    },
    
  ]
}

Check this https://mongoplayground.net/p/Wg144t8fvso

Upvotes: 1

Views: 150

Answers (1)

G2 Jakhmola
G2 Jakhmola

Reputation: 811

You can try

"count": {
        "$size": {
          "$cond": [
            {
              "$isArray": "$result.template"
            },
            "$result.template",
            []
          ]
        }
      }

https://mongoplayground.net/p/K0shGUYRMsM

Upvotes: 2

Related Questions