1

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

1 Answer 1

2

You can try

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

https://mongoplayground.net/p/K0shGUYRMsM

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.