我想用SQL查询一些东西,比如查询:

SELECT * FROM users  WHERE name LIKE '%m%'

如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。


当前回答

还可以按如下方式使用通配符过滤器:

{"query": { "wildcard": {"lookup_field":"search_string*"}}}

请务必使用*。

其他回答

您可以使用where语句构建任何JavaScript脚本:

db.myCollection.find( { $where: "this.name.toLowerCase().indexOf('m') >= 0" } );

参考:$where

Use:

db.customer.find({"customerid": {"$regex": "CU_00000*", "$options": "i"}}).pretty()

当我们搜索字符串模式时,最好使用上面的模式,因为我们不确定大小写。

MongoRegex已被弃用。

使用MongoDB \ BSON \ Regex:

$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
db.users.insert({name: 'patrick'})
db.users.insert({name: 'petra'})
db.users.insert({name: 'pedro'})

因此:

For:

db.users.find({name: /a/})  // Like '%a%'

输出:patrick,petra

For:

db.users.find({name: /^pa/}) // Like 'pa%'

输出:patrick

For:

db.users.find({name: /ro$/}) // Like '%ro'

输出:pedro

使用如下匹配的正则表达式。“i”显示不区分大小写。

var collections = mongoDatabase.GetCollection("Abcd");

var queryA = Query.And(
         Query.Matches("strName", new BsonRegularExpression("ABCD", "i")), 
         Query.Matches("strVal", new BsonRegularExpression("4121", "i")));

var queryB = Query.Or(
       Query.Matches("strName", new BsonRegularExpression("ABCD","i")),
       Query.Matches("strVal", new BsonRegularExpression("33156", "i")));

var getA = collections.Find(queryA);
var getB = collections.Find(queryB);