如何在mongodb和mysql中搜索子字符串?

yc0p9oo0  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(300)

我的数据库中的“用户”集合/表数据如下所示this:-

{
 _id: 1,
 name: "Vikas",
 subject: "Computers"
},
{
 _id: 2,
 name: "Hello",
 subject: "Computers"
},
{
 _id: 3,
 name: "Abc",
 subject: "Mechanical"
}

下面的查询将给出机械测试的结果data:-
mongodb:- db.test.find({subject: /mech/i}) ->
mysql:-

select * from test where subject like "%mech%"

但是我想这样搜索,如果我搜索“机械数据”,那么这将不会给出机械数据的结果。
我希望我能澄清我的问题。提前谢谢!

fdbelqdn

fdbelqdn1#

(与mysql相关)
没有一种搜索机制能够充分理解各种语言,从而认识到“机械数据”和“机械数据”是相同的。
你可以,在个人的基础上,这样做,但不是在一般情况下。

REGEXP "mechanical ?data"

这个 ? 表示“可选空间”。

LIKE "%mechanical%data"

也可以找到“机械数据”和“机械数据”。不过,它也会找到“机械foobar数据”

cs7cruho

cs7cruho2#

For MongoDB    
db.test.find({subject: /^mech$/i}) //Search exact word
db.test.find({subject: /mech$/i}) //Search word which ending with "mech"
db.test.find({subject: /^mech/i}) //Search word which start with "mech"
db.test.find({subject: /mech/i}) //Search word at any position

For Mysql
select * from test where subject like "mech" //Search exact word
select * from test where subject like "%mech" //Search word which ending with "metch"
select * from test where subject like "mech%" //Search word which start with "metch"
select * from test where subject like "%mech%" //Search word at any position

相关问题