-1

hi i have a little problem, i hope someone know that how can i deal with this problem.

  {
    "isim": "This is topic - 2",
    "resim": "anywhere2.png",
    "ozellik": {
      "detay": ["qv", "asv", "asd" , "vx"],
      "bilgi": ["xc", "bv", "hjm" , "sax"]
    }
  },

  {
    "isim": "This is topic - 1",
    "resim": "anywhere.png",
    "ozellik": {
      "detay": ["sa", "as", "de", "ed"],
      "bilgi": ["bv", "cv", "asd", "dsa"]
    }
  }

this is my db, I can do that: bilgi[2] like this

{ $project: {
        _id: 0,
        isim: 1,
        boyut: { $arrayElemAt: ["$ozellik.bilgi", -2] },
      }}

and this code return following lines:

{
    "isim": "This is topic - 2",
    "boyut": "hjm"
  },

  {
    "isim": "This is topic - 1",
    "boyut": "asd"
  }

here is, i want to know what is length of "hjm" or "asd"

this is not work for me : String field value length in array in mongoDB

and i try this :

boyut: { $strLenCP : {$arrayElemAt: ["$ozellik.bilgi", -2]} },

and node js is say that, Screenshot

MongoError: $strLenCP requires a string argument, found: missing
turivishal
  • 34,368
  • 7
  • 36
  • 59

1 Answers1

1

Its happening when it search for $arrayElemAt position -2, if array element size is less than or equal to 1 then, this function will return null, and $strLenCP operator supports only string type,

You can use $ifNull to prevent this error,

  {
    $project: {
      _id: 0,
      isim: 1,
      boyut: {
        $strLenCP: {
          $ifNull: [
            { $arrayElemAt: ["$ozellik.bilgi", -2] },
            ""
          ]
        }
      }
    }
  }

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59