【问题标题】:How can I use 'Not Like' operator in MongoDB如何在 MongoDB 中使用“不喜欢”运算符
【发布时间】:2013-12-09 02:52:10
【问题描述】:

我可以通过pymongo 使用 SQL Like 运算符,

db.test.find({'c':{'$regex':'ttt'}})

但是如何使用Not Like 运算符呢?

我试过了

db.test.find({'c':{'$not':{'$regex':'ttt'}})

但出现错误:

OperationFailure: $not 不能有正则表达式

【问题讨论】:

  • 我知道这有点晚了,但在 MongoDB 4.2 中,$not$regex 运算符的组合似乎对我有用。
  • db.collectionname.find( { column: { $not: /^ttt$/ } } ) 这很简单。
  • $not$regex 从 MongoDB 4.0.7 开始可以一起使用。
  • @Milan 是的,这很容易,因为它是 8 年前作为答案发布的。您的评论没有帮助。

标签: regex mongodb mongodb-query pymongo sql-like


【解决方案1】:

来自docs

$not 运算符不支持使用 $regex 的操作 操作员。而是使用 // 或在您的驱动程序接口中,使用您的 语言的正则表达式创建正则表达式的能力 对象。考虑以下使用模式匹配的示例 表达式 //:

db.inventory.find( { item: { $not: /^p.*/ } } )

编辑(@idbentley):

{$regex: 'ttt'} 一般相当于 mongodb 中的/ttt/,所以你的查询会变成:

db.test.find({c: {$not: /ttt/}}

EDIT2(@KyungHoon Kim):

python 中,以下一个有效:

'c':{'$not':re.compile('ttt')}

【讨论】:

  • 要明确,{$regex: 'ttt'} 在 mongodb 中一般相当于/ttt/,所以你的查询会变成db.test.find({c: {$not: /ttt/}}
  • @idbentley 谢谢。我用你的说明更新了我的答案。
  • 非常感谢。对于其他人,我使用了'c':{'$not':re.compile('ttt')}。当然需要import re
  • 太棒了。为了后代,我还将您的评论添加到答案中。
  • 这似乎与 $ne 和 $regex 的情况相同。任何人都可以确认这一点,或者至少补充一下吗?
【解决方案2】:

您可以使用不包含单词的正则表达式。此外,您可以使用$options => i 进行不区分大小写的搜索。

不包含string

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

不区分大小写string

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})

string开头

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})

string结尾

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})

包含string

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

将此作为书签保存,并作为您可能需要的任何其他更改的参考。 http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 2014-02-08
    相关资源
    最近更新 更多