【问题标题】:MongoDB - How to query for strings which doesn't have any spaces (omit the strings with spaces) with lengthMongoDB - 如何用长度查询没有任何空格的字符串(省略带空格的字符串)
【发布时间】:2020-03-17 00:53:02
【问题描述】:

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

文件格式示例:

{
    "_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

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

感谢任何帮助!

【问题讨论】:

  • 你的 MongoDB 版本是多少?
  • 4.2 mate.....

标签: mongodb mongodb-query aggregation-framework pymongo


【解决方案1】:

更新:

我找到了另一种方法(可能很简单),它应该适用于版本 >=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-Playground

旧:

在 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-Playground

【讨论】:

  • 哇 @whoami 我只是喜欢你解释它的方式,谢谢你的朋友.....+1,如果有一些有用的链接来学习 mongo 会很高兴(除了文档:))
  • @Codenewbie : 在这里注册 :: university.mongodb.com ,它有免费课程(直接来自 MongoDB)
  • 嘿@whoami,你能帮我问一下吗stackoverflow.com/questions/60810426/…
猜你喜欢
  • 1970-01-01
  • 2013-05-12
  • 2013-07-04
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多