-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
1

1 Answer 1

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

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.