【问题标题】:mongodb how to find a length of string in a arraymongodb如何在数组中查找字符串的长度
【发布时间】:2020-09-10 15:04:58
【问题描述】:

您好,我有一个小问题,我希望有人知道我该如何处理这个问题。

  {
    "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"]
    }
  }

这是我的数据库,我可以这样做: bilgi[2] 这样的

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

并且此代码返回以下行:

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

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

这里是,我想知道“hjm”或“asd”的长度是多少

这对我不起作用:String field value length in array in mongoDB

我试试这个:

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

node js 就是这么说的,Screenshot

MongoError: $strLenCP requires a string argument, found: missing

【问题讨论】:

标签: node.js mongodb


【解决方案1】:

它在搜索$arrayElemAt位置-2时发生,如果数组元素大小小于等于1则该函数将返回null,而$strLenCP运算符只支持字符串类型,

你可以使用$ifNull来防止这个错误,

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

Playground

【讨论】:

    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多