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

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

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


当前回答

使用聚合子字符串搜索(带索引!!!):

db.collection.aggregate([{
        $project : {
            fieldExists : {
                $indexOfBytes : ['$field', 'string']
            }
        }
    }, {
        $match : {
            fieldExists : {
                $gt : -1
            }
        }
    }, {
        $limit : 5
    }
]);

其他回答

为了以防万一,有人正在寻找一种SQL LIKE类型的查询,以查找包含字符串数组而不是字符串的键,这里是:

db.users.find({"name": {$in: [/.*m.*/]}})

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

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

参考:$where

前面的答案完美地回答了有关MongoDB核心查询的问题。但当使用基于模式的搜索查询时,例如:

{“keywords”:{“$regex”:“^toron.*”}}

or

{“关键字”:{“$regex”:“^toron”}}

在带有@query注释的Spring Boot JPA存储库查询中,使用如下查询:

@Query(value = "{ keyword : { $regex : ?0 }  }")
List<SomeResponse> findByKeywordContainingRegex(String keyword);

呼叫应为:

List<SomeResponse> someResponseList =    someRepository.findByKeywordsContainingRegex("^toron");

List<SomeResponse> someResponseList =    someRepository.findByKeywordsContainingRegex("^toron.*");

但千万不要使用:

List<SomeResponse> someResponseList = someRepository.findByKeywordsContainingRegex("/^toron/");

List<SomeResponse> someResponseList =someRepository.findByKeywordsContainingRegex("/^toron.*/");

需要注意的一点是:每次?@Query语句中的0字段替换为双引号字符串。因此,在这些情况下不应使用正斜杠(/)!在搜索模式中始终使用双引号!!例如,在/^toron/或/^toron上使用“^toron”或“^toron.*”*/

MongoRegex已被弃用。

使用MongoDB \ BSON \ Regex:

$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
>> db.car.distinct('name')
[ "honda", "tat", "tata", "tata3" ]

>> db.car.find({"name":/. *ta.* /})