首页 > 解决方案 > MongoDB - 如何用长度查询没有任何空格的字符串(省略带空格的字符串)

问题描述

我已将长度匹配的文档查询为:

文件样本格式:

{
    "_id": {
        "$oid": "5e158e2de6facf7181cc368f"
    },
    "word": "as luck would have it",
}

查询为:

{$where: "this.word.length == 20 "}

这符合以下内容:

{
    "_id": {
        "$oid": "5e158e30e6facf7181cc3bdb"
    },
    "word": "adrenocorticotrophic",
}

{
    "_id": {
        "$oid": "5e158e2ee6facf7181cc38cf"
    },
    "word": "attributive genitive",
}

但我只想不匹配adrenocorticotrophic带有空格的单词attributive genitive

我可以知道我怎么能像上面那样匹配?

任何帮助表示赞赏!

标签: mongodbmongodb-queryaggregation-frameworkpymongo

解决方案


更新 :

我找到了另一种方法(可能很简单),它应该与 version >= 一起使用3.4,试试这个:

/** When you split a string on a delimiter(space in your requirement) it would split string into an array of elements, 
* if no space in string then it would be only one element in array, then get a size & get docs having size less than 2 */

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $lt: [
          {
            $size: {
              $split: [
                "$word", // word should not be null or '' (can be empty ' ')
                " "
              ]
            }
          },
          2
        ]
      }
    }
  }
])

测试: MongoDB-游乐场

老的 :

在 MongoDB 版本 >=4.2上,您可以使用$regexMatch做到这一点:

db.collection.aggregate([
  /** A new field gets added to be true if word has spaces else be false */
  {
    $addFields: {
      wordHasSpaces: {
        $regexMatch: {
          input: "$word",
          regex: /\w+\s\w+/ /** This regex exp works if your string has plain characters A-Z */
        }
      }
    }
  },
  /** Remove docs where word has spaces */
  { $match: { wordHasSpaces: false } },
  /** Remove newly added unnecessary field */
  { $project: { wordHasSpaces: 0 } }
]);

同样对于您现有的代码,您可以停止使用$where通常用于在查询中执行 .js 代码的性能较低的代码,因此在 MongoDB v >= 上,3.4您可以使用$strLenCP

db.collection.aggregate([{$match : {$expr: {$eq : [{ $strLenCP:'$word'}, 20]}}}]) /** $expr is kind of replacement to $where */

测试: MongoDB-游乐场


推荐阅读