如何在MongoDB中使用'Not Like'运算符

Kyu*_*Kim 88 regex mongodb pymongo mongodb-query sql-like

我使用pymongo的SQL'Like'运算符,

db.test.find({'c':{'$regex':'ttt'}})
Run Code Online (Sandbox Code Playgroud)

但是我如何使用'不喜欢'运算符?

我试过了

db.test.find({'c':{'$not':{'$regex':'ttt'}})
Run Code Online (Sandbox Code Playgroud)

shx*_*hx2 125

来自文档:

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

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

编辑(@idbentley):

{$regex: 'ttt'}通常等同/ttt/于mongodb,因此您的查询将成为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 /}} `. (2认同)

Som*_*luk 50

你可以使用不包含单词的正则表达式.此外,您可以使用$options => i不敏感搜索的情况.

不包含 string

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

确切的不区分大小写 string

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)

以..开始 string

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)

以..结束 string

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)

包含 string

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)

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