如何用“like”查询MongoDB ?

时间:2022-06-03 03:51:43

I want to query something as SQL's like query:

我想查询一些像SQL这样的查询:

select * 
from users 
where name like '%m%'

How to do the same in MongoDB?
I can't find a operator for like in the documentations.

如何在MongoDB中做同样的事情?我在文件中找不到操作员。

32 个解决方案

#1


1391  

That would have to be:

必须是:

db.users.find({"name": /.*m.*/})

or, similar:

或者,类似:

db.users.find({"name": /m/})

You're looking for something that contains "m" somewhere (SQL's '%' operator is equivalent to Regexp's '.*'), not something that has "m" anchored to the beginning of the string.

您正在寻找某个地方包含“m”的东西(SQL的'%'操作符相当于Regexp的'.*'),而不是锚定在字符串开头的“m”。

#2


229  

db.users.insert({name: 'paulo'})
db.users.insert({name: 'patric'})
db.users.insert({name: 'pedro'})

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

out: paulo, patric

:保罗,帕特里克

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

out: paulo, patric

:保罗,帕特里克

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

out: pedro

:佩德罗

#3


179  

In

  • PyMongo using Python
  • 使用Python PyMongo
  • Mongoose using Node.js
  • 猫鼬使用node . js
  • Jongo, using Java
  • Jongo,使用Java
  • mgo, using Go
  • 采用,使用

you can do:

你能做什么:

db.users.find({'name': {'$regex': 'sometext'}})

#4


73  

In PHP, you could use following code:

在PHP中,可以使用以下代码:

$collection->find(array('name'=> array('$regex' => 'm'));

#5


41  

You would use regex for that in mongo.

在mongo你会使用regex。

e.g: db.users.find({"name": /^m/})

e。g:db.users。找到({“名称”:/ ^ m / })

#6


24  

If using node.js, it says that you can write this:

如果使用节点。js,它说你可以这样写:

db.collection.find( { field: /acme.*corp/i } );
//or
db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );

Also, you can write this:

你也可以这样写:

db.collection.find( { field: new RegExp('acme.*corp', 'i') } );

#7


21  

There are already many answers. I am giving different types of requirements and solutions for string search with regex.

已经有很多答案了。我使用regex为字符串搜索提供不同类型的需求和解决方案。

You can do with regex which contain word i.e like. Also you can use $options => i for case insensitive search

您可以使用包含单词i的regex。e。也可以使用$options =>,以区分大小写搜索。

Contains string

包含字符串

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

Doesn't Contains string only with regex

不包含只有regex的字符串。

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

Exact case insensitive string

完全不分大小写字符串

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

Start with string

从字符串开始

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

End with string

结尾字符串

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

Keep this as a bookmark, and a reference for any other alterations you may need.

把它作为书签,作为你可能需要的任何其他修改的参考。

#8


14  

Already u got the answers but to match regex with case insensitivity

您已经得到了答案,但是要将regex与case不敏感匹配

You could use the following query

您可以使用以下查询

db.users.find ({ "name" : /m/i } ).pretty()

The i in the /m/i indicates case insensitivity and .pretty() provides a more pretty output

/m/i中的i表示大小写不敏感,而.pretty()提供了更漂亮的输出

#9


11  

For Mongoose in Node.js

猫鼬在node . js

db.users.find({'name': {'$regex': '.*sometext.*'}})

#10


10  

You can use the new feature of 2.6 mongodb:

可以使用2.6 mongodb的新特性:

db.foo.insert({desc: "This is a string with text"});
db.foo.insert({desc:"This is a another string with Text"});
db.foo.ensureIndex({"desc":"text"});
db.foo.find({
    $text:{
        $search:"text"
    }
});

#11


10  

You have 2 choices:

你有2个选择:

db.users.find({"name": /string/})

or

db.users.find({"name": {"$regex": "string", "$options": "i"}})

On second one you have more options, like "i" in options to find using case insensitive. And about the "string", you can use like ".string." (%string%), or "string.*" (string%) and ".*string) (%string) for example. You can use regular expression as you want.

在第二个选项中,您有更多的选项,比如在选项中查找不区分大小写的“i”。关于"string"你可以用"。string"字符串(% %),或“字符串。*“(字符串%)和”.*字符串)(%字符串)。可以任意使用正则表达式。

Enjoy!

享受吧!

#12


8  

For PHP mongo Like.
I had several issues with php mongo like. i found that concatenating the regex params helps in some situations PHP mongo find field starts with. I figured I would post on here to contribute to the more popular thread

为PHP mongo。我对php mongo有几个问题。我发现,在某些情况下,连接regex params有助于PHP mongo查找字段。我想我可以在这里发布,为更流行的帖子做贡献

e.g

db()->users->insert(['name' => 'john']);
db()->users->insert(['name' => 'joe']);
db()->users->insert(['name' => 'jason']);

// starts with
$like_var = 'jo';
$prefix = '/^';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
output: (joe, john)

// contains
$like_var = 'j';
$prefix = '/';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);

output: (joe, john, jason)

#13


8  

In nodejs project and use mongoose use Like query

在nodejs项目中使用mongoose查询

var User = mongoose.model('User');

var searchQuery={};
searchQuery.email = req.query.email;
searchQuery.name = {$regex: req.query.name, $options: 'i'};
User.find(searchQuery, function(error, user) {
                if(error || user === null) {
                    return res.status(500).send(error);
                }
                return res.status(200).send(user);
            });

#14


6  

You can use where statement to build any JS script:

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

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

Reference: http://docs.mongodb.org/manual/reference/operator/where/

参考:http://docs.mongodb.org/manual/reference/operator/where/

#15


6  

In SQL, the ‘like’ query is looks like this :

在SQL中,“like”查询如下:

select * from users where name like '%m%'

In MongoDB console, it looks like this :

在MongoDB控制台,它是这样的:

db.users.find({"name": /m/})     // Not JSON formatted

db.users.find({"name": /m/}).pretty()  // JSON formatted

In addion pretty() method will in all the places where produce formatted JSON structure which is more readable.

在addion pretty()方法中,将会在所有可以生成格式化的JSON结构的地方使用,这样更容易阅读。

#16


6  

Use regular expressions matching as below. The 'i' shows case insensitivity.

使用正则表达式匹配如下所示。“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);

#17


5  

In Go and the mgo driver:

在Go和mgo司机:

Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)

where result is the struct instance of the sought after type

搜索后类型的结构实例在哪里

#18


4  

Like Query would be as shown below

Like查询将如下所示

db.movies.find({title: /.*Twelve Monkeys.*/}).sort({regularizedCorRelation : 1}).limit(10);

for scala ReactiveMongo api,

因为scala ReactiveMongo api,

val query = BSONDocument("title" -> BSONRegex(".*"+name+".*", "")) //like
val sortQ = BSONDocument("regularizedCorRelation" -> BSONInteger(1))
val cursor = collection.find(query).sort(sortQ).options(QueryOpts().batchSize(10)).cursor[BSONDocument]

#19


4  

With MongoDB Compass, you need to use the strict mode syntax, as such:

对于MongoDB Compass,您需要使用严格的模式语法,比如:

{ "text": { "$regex": "^Foo.*", "$options": "i" } }

(In MongoDB Compass, it's important that you use " instead of ')

(在MongoDB Compass中,使用“而不是”是很重要的)

#20


3  

If you are using Spring-Data Mongodb You can do this in this way:

如果您正在使用Spring-Data Mongodb,您可以这样做:

String tagName = "m";
Query query = new Query();
query.limit(10);        
query.addCriteria(Criteria.where("tagName").regex(tagName));

#21


3  

As Mongo shell support regex, that's completely possible.

由于Mongo shell支持regex,这是完全可能的。

db.users.findOne({"name" : /.*sometext.*/});

If we want the query to be case-insensitive, we can use "i" option, like shown below:

如果我们希望查询不区分大小写,我们可以使用“i”选项,如下所示:

db.users.findOne({"name" : /.*sometext.*/i});

#22


3  

If you want 'Like' search in mongo then you should go with $regex by using this query will be

如果你想在mongo中搜索“Like”,那么你应该使用$regex,使用这个查询

db.product.find({name:{$regex:/m/i}})

db.product.find({ name:{ $正则表达式:/ m /我} })

for more you can read the documentation as well. https://docs.mongodb.com/manual/reference/operator/query/regex/

更多信息,您也可以阅读文档。https://docs.mongodb.com/manual/reference/operator/query/regex/

#23


3  

It seems that there are reasons for using both the javascript /regex_pattern/ pattern as well as the mongo {'$regex': 'regex_pattern'} pattern. See: MongoBD RegEx Syntax Restrictions

似乎有理由同时使用javascript /regex_pattern/模式以及mongo {'$regex': 'regex_pattern'}模式。参见:MongoBD RegEx语法限制

This is not a complete RegEx tutorial, but I was inspired to run these tests after seeing a highly voted ambiguous post above.

这并不是一个完整的RegEx教程,但是我在看到一个高度投票的模糊的帖子后,被激发了运行这些测试。

> ['abbbb','bbabb','bbbba'].forEach(function(v){db.test_collection.insert({val: v})})

> db.test_collection.find({val: /a/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.*a.*/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.+a.+/})
{ "val" : "bbabb" }

> db.test_collection.find({val: /^a/})
{ "val" : "abbbb" }

> db.test_collection.find({val: /a$/})
{ "val" : "bbbba" }

> db.test_collection.find({val: {'$regex': 'a$'}})
{ "val" : "bbbba" }

#24


2  

I found a free tool to translate MYSQL queries to MongoDB. http://www.querymongo.com/ I checked with several queries. as i see almost all them are correct. According to that, The answer is

我找到了一个免费的工具,可以将MYSQL查询翻译成MongoDB。http://www.querymongo.com/我检查了几个查询。在我看来,它们几乎都是正确的。根据这一点,答案是

db.users.find({
    "name": "%m%"
});

#25


1  

MongoRegex has been deprecated.
Use MongoDB\BSON\Regex

MongoRegex已弃用。使用MongoDB \ BSON \正则表达式

$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor

#26


1  

If you're using PHP, you can use MongoDB_DataObject wrapper like below:

如果使用PHP,可以使用MongoDB_DataObject包装器,如下所示:

$model = new MongoDB_DataObject();

$model->query("select * from users where name like '%m%'");

while($model->fetch()) {
    var_dump($model);
}

OR:

或者:

$model = new MongoDB_DataObject('users);

$model->whereAdd("name like '%m%'");

$model->find();

while($model->fetch()) {
    var_dump($model);
}

#27


1  

FullName like 'last' with status==’Pending’ between two dates:

姓“last”,状态=“Pending”在两个日期之间:

db.orders.find({
      createdAt:{$gt:ISODate("2017-04-25T10:08:16.111Z"),
      $lt:ISODate("2017-05-05T10:08:16.111Z")},
      status:"Pending",
      fullName:/last/}).pretty();

status== 'Pending' and orderId LIKE ‘PHA876174’:

status= " Pending "和orderId " PHA876174 ":

db.orders.find({
     status:"Pending",
     orderId:/PHA876174/
     }).pretty();

#28


1  

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

When we are searching for string patterns, always it is better to use the above pattern as when we are not sure about case. Hope that helps!!!

当我们搜索字符串模式时,最好使用上面的模式,就像我们不确定大小写一样。希望帮助! ! !

#29


1  

Use aggregation substring search (with index!!!):

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

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

#30


1  

Regex are expensive are process.

Regex是昂贵的过程。

Another way is to create an index of text and then search it using $search.

另一种方法是创建文本索引,然后使用$search对其进行搜索。

Create a text Index of fields you want to make searchable:

创建你想要搜索的字段的文本索引:

db.collection.createIndex({name: 'text', otherField: 'text'});

Search for a string in text index:

在文本索引中搜索字符串:

db.collection.find({
  '$text'=>{'$search': "The string"}
})

#1


1391  

That would have to be:

必须是:

db.users.find({"name": /.*m.*/})

or, similar:

或者,类似:

db.users.find({"name": /m/})

You're looking for something that contains "m" somewhere (SQL's '%' operator is equivalent to Regexp's '.*'), not something that has "m" anchored to the beginning of the string.

您正在寻找某个地方包含“m”的东西(SQL的'%'操作符相当于Regexp的'.*'),而不是锚定在字符串开头的“m”。

#2


229  

db.users.insert({name: 'paulo'})
db.users.insert({name: 'patric'})
db.users.insert({name: 'pedro'})

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

out: paulo, patric

:保罗,帕特里克

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

out: paulo, patric

:保罗,帕特里克

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

out: pedro

:佩德罗

#3


179  

In

  • PyMongo using Python
  • 使用Python PyMongo
  • Mongoose using Node.js
  • 猫鼬使用node . js
  • Jongo, using Java
  • Jongo,使用Java
  • mgo, using Go
  • 采用,使用

you can do:

你能做什么:

db.users.find({'name': {'$regex': 'sometext'}})

#4


73  

In PHP, you could use following code:

在PHP中,可以使用以下代码:

$collection->find(array('name'=> array('$regex' => 'm'));

#5


41  

You would use regex for that in mongo.

在mongo你会使用regex。

e.g: db.users.find({"name": /^m/})

e。g:db.users。找到({“名称”:/ ^ m / })

#6


24  

If using node.js, it says that you can write this:

如果使用节点。js,它说你可以这样写:

db.collection.find( { field: /acme.*corp/i } );
//or
db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );

Also, you can write this:

你也可以这样写:

db.collection.find( { field: new RegExp('acme.*corp', 'i') } );

#7


21  

There are already many answers. I am giving different types of requirements and solutions for string search with regex.

已经有很多答案了。我使用regex为字符串搜索提供不同类型的需求和解决方案。

You can do with regex which contain word i.e like. Also you can use $options => i for case insensitive search

您可以使用包含单词i的regex。e。也可以使用$options =>,以区分大小写搜索。

Contains string

包含字符串

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

Doesn't Contains string only with regex

不包含只有regex的字符串。

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

Exact case insensitive string

完全不分大小写字符串

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

Start with string

从字符串开始

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

End with string

结尾字符串

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

Keep this as a bookmark, and a reference for any other alterations you may need.

把它作为书签,作为你可能需要的任何其他修改的参考。

#8


14  

Already u got the answers but to match regex with case insensitivity

您已经得到了答案,但是要将regex与case不敏感匹配

You could use the following query

您可以使用以下查询

db.users.find ({ "name" : /m/i } ).pretty()

The i in the /m/i indicates case insensitivity and .pretty() provides a more pretty output

/m/i中的i表示大小写不敏感,而.pretty()提供了更漂亮的输出

#9


11  

For Mongoose in Node.js

猫鼬在node . js

db.users.find({'name': {'$regex': '.*sometext.*'}})

#10


10  

You can use the new feature of 2.6 mongodb:

可以使用2.6 mongodb的新特性:

db.foo.insert({desc: "This is a string with text"});
db.foo.insert({desc:"This is a another string with Text"});
db.foo.ensureIndex({"desc":"text"});
db.foo.find({
    $text:{
        $search:"text"
    }
});

#11


10  

You have 2 choices:

你有2个选择:

db.users.find({"name": /string/})

or

db.users.find({"name": {"$regex": "string", "$options": "i"}})

On second one you have more options, like "i" in options to find using case insensitive. And about the "string", you can use like ".string." (%string%), or "string.*" (string%) and ".*string) (%string) for example. You can use regular expression as you want.

在第二个选项中,您有更多的选项,比如在选项中查找不区分大小写的“i”。关于"string"你可以用"。string"字符串(% %),或“字符串。*“(字符串%)和”.*字符串)(%字符串)。可以任意使用正则表达式。

Enjoy!

享受吧!

#12


8  

For PHP mongo Like.
I had several issues with php mongo like. i found that concatenating the regex params helps in some situations PHP mongo find field starts with. I figured I would post on here to contribute to the more popular thread

为PHP mongo。我对php mongo有几个问题。我发现,在某些情况下,连接regex params有助于PHP mongo查找字段。我想我可以在这里发布,为更流行的帖子做贡献

e.g

db()->users->insert(['name' => 'john']);
db()->users->insert(['name' => 'joe']);
db()->users->insert(['name' => 'jason']);

// starts with
$like_var = 'jo';
$prefix = '/^';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
output: (joe, john)

// contains
$like_var = 'j';
$prefix = '/';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);

output: (joe, john, jason)

#13


8  

In nodejs project and use mongoose use Like query

在nodejs项目中使用mongoose查询

var User = mongoose.model('User');

var searchQuery={};
searchQuery.email = req.query.email;
searchQuery.name = {$regex: req.query.name, $options: 'i'};
User.find(searchQuery, function(error, user) {
                if(error || user === null) {
                    return res.status(500).send(error);
                }
                return res.status(200).send(user);
            });

#14


6  

You can use where statement to build any JS script:

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

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

Reference: http://docs.mongodb.org/manual/reference/operator/where/

参考:http://docs.mongodb.org/manual/reference/operator/where/

#15


6  

In SQL, the ‘like’ query is looks like this :

在SQL中,“like”查询如下:

select * from users where name like '%m%'

In MongoDB console, it looks like this :

在MongoDB控制台,它是这样的:

db.users.find({"name": /m/})     // Not JSON formatted

db.users.find({"name": /m/}).pretty()  // JSON formatted

In addion pretty() method will in all the places where produce formatted JSON structure which is more readable.

在addion pretty()方法中,将会在所有可以生成格式化的JSON结构的地方使用,这样更容易阅读。

#16


6  

Use regular expressions matching as below. The 'i' shows case insensitivity.

使用正则表达式匹配如下所示。“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);

#17


5  

In Go and the mgo driver:

在Go和mgo司机:

Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)

where result is the struct instance of the sought after type

搜索后类型的结构实例在哪里

#18


4  

Like Query would be as shown below

Like查询将如下所示

db.movies.find({title: /.*Twelve Monkeys.*/}).sort({regularizedCorRelation : 1}).limit(10);

for scala ReactiveMongo api,

因为scala ReactiveMongo api,

val query = BSONDocument("title" -> BSONRegex(".*"+name+".*", "")) //like
val sortQ = BSONDocument("regularizedCorRelation" -> BSONInteger(1))
val cursor = collection.find(query).sort(sortQ).options(QueryOpts().batchSize(10)).cursor[BSONDocument]

#19


4  

With MongoDB Compass, you need to use the strict mode syntax, as such:

对于MongoDB Compass,您需要使用严格的模式语法,比如:

{ "text": { "$regex": "^Foo.*", "$options": "i" } }

(In MongoDB Compass, it's important that you use " instead of ')

(在MongoDB Compass中,使用“而不是”是很重要的)

#20


3  

If you are using Spring-Data Mongodb You can do this in this way:

如果您正在使用Spring-Data Mongodb,您可以这样做:

String tagName = "m";
Query query = new Query();
query.limit(10);        
query.addCriteria(Criteria.where("tagName").regex(tagName));

#21


3  

As Mongo shell support regex, that's completely possible.

由于Mongo shell支持regex,这是完全可能的。

db.users.findOne({"name" : /.*sometext.*/});

If we want the query to be case-insensitive, we can use "i" option, like shown below:

如果我们希望查询不区分大小写,我们可以使用“i”选项,如下所示:

db.users.findOne({"name" : /.*sometext.*/i});

#22


3  

If you want 'Like' search in mongo then you should go with $regex by using this query will be

如果你想在mongo中搜索“Like”,那么你应该使用$regex,使用这个查询

db.product.find({name:{$regex:/m/i}})

db.product.find({ name:{ $正则表达式:/ m /我} })

for more you can read the documentation as well. https://docs.mongodb.com/manual/reference/operator/query/regex/

更多信息,您也可以阅读文档。https://docs.mongodb.com/manual/reference/operator/query/regex/

#23


3  

It seems that there are reasons for using both the javascript /regex_pattern/ pattern as well as the mongo {'$regex': 'regex_pattern'} pattern. See: MongoBD RegEx Syntax Restrictions

似乎有理由同时使用javascript /regex_pattern/模式以及mongo {'$regex': 'regex_pattern'}模式。参见:MongoBD RegEx语法限制

This is not a complete RegEx tutorial, but I was inspired to run these tests after seeing a highly voted ambiguous post above.

这并不是一个完整的RegEx教程,但是我在看到一个高度投票的模糊的帖子后,被激发了运行这些测试。

> ['abbbb','bbabb','bbbba'].forEach(function(v){db.test_collection.insert({val: v})})

> db.test_collection.find({val: /a/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.*a.*/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.+a.+/})
{ "val" : "bbabb" }

> db.test_collection.find({val: /^a/})
{ "val" : "abbbb" }

> db.test_collection.find({val: /a$/})
{ "val" : "bbbba" }

> db.test_collection.find({val: {'$regex': 'a$'}})
{ "val" : "bbbba" }

#24


2  

I found a free tool to translate MYSQL queries to MongoDB. http://www.querymongo.com/ I checked with several queries. as i see almost all them are correct. According to that, The answer is

我找到了一个免费的工具,可以将MYSQL查询翻译成MongoDB。http://www.querymongo.com/我检查了几个查询。在我看来,它们几乎都是正确的。根据这一点,答案是

db.users.find({
    "name": "%m%"
});

#25


1  

MongoRegex has been deprecated.
Use MongoDB\BSON\Regex

MongoRegex已弃用。使用MongoDB \ BSON \正则表达式

$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor

#26


1  

If you're using PHP, you can use MongoDB_DataObject wrapper like below:

如果使用PHP,可以使用MongoDB_DataObject包装器,如下所示:

$model = new MongoDB_DataObject();

$model->query("select * from users where name like '%m%'");

while($model->fetch()) {
    var_dump($model);
}

OR:

或者:

$model = new MongoDB_DataObject('users);

$model->whereAdd("name like '%m%'");

$model->find();

while($model->fetch()) {
    var_dump($model);
}

#27


1  

FullName like 'last' with status==’Pending’ between two dates:

姓“last”,状态=“Pending”在两个日期之间:

db.orders.find({
      createdAt:{$gt:ISODate("2017-04-25T10:08:16.111Z"),
      $lt:ISODate("2017-05-05T10:08:16.111Z")},
      status:"Pending",
      fullName:/last/}).pretty();

status== 'Pending' and orderId LIKE ‘PHA876174’:

status= " Pending "和orderId " PHA876174 ":

db.orders.find({
     status:"Pending",
     orderId:/PHA876174/
     }).pretty();

#28


1  

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

When we are searching for string patterns, always it is better to use the above pattern as when we are not sure about case. Hope that helps!!!

当我们搜索字符串模式时,最好使用上面的模式,就像我们不确定大小写一样。希望帮助! ! !

#29


1  

Use aggregation substring search (with index!!!):

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

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

#30


1  

Regex are expensive are process.

Regex是昂贵的过程。

Another way is to create an index of text and then search it using $search.

另一种方法是创建文本索引,然后使用$search对其进行搜索。

Create a text Index of fields you want to make searchable:

创建你想要搜索的字段的文本索引:

db.collection.createIndex({name: 'text', otherField: 'text'});

Search for a string in text index:

在文本索引中搜索字符串:

db.collection.find({
  '$text'=>{'$search': "The string"}
})