我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
您已经得到了答案,但要匹配不区分大小写的正则表达式,可以使用以下查询:
db.users.find ({ "name" : /m/i } ).pretty()
/m/i中的i表示不区分大小写,.pretty()提供了更漂亮的输出。
其他回答
Use:
const indexSearch = await UserModel.find(
{ $text: { $search: filter } },
);
if (indexSearch.length) {
return indexSearch;
}
return UserModel.find(
{
$or: [
{ firstName: { $regex: `^${filter}`, $options: 'i' } },
{ lastName: { $regex: `^${filter}`, $options: 'i' } },
{ middleName: { $regex: `^${filter}`, $options: 'i' } },
{ email: { $regex: `^${filter}`, $options: 'i' } },
],
},
);
我使用了正则表达式和“索引”的组合。
将模板文字与变量一起使用也有效:
{“firstname”:{$regex:`^${req.body.firstname}.*`,$options:'si'}}
正则表达式的处理成本很高。
另一种方法是创建文本索引,然后使用$search进行搜索。
创建要搜索的字段的文本索引:
db.collection.createIndex({name: 'text', otherField: 'text'});
在文本索引中搜索字符串:
db.collection.find({
'$text'=>{'$search': "The string"}
})
如果您有字符串变量,则必须将其转换为正则表达式,因此MongoDB将对其使用类似的语句。
const name = req.query.title; //John
db.users.find({ "name": new Regex(name) });
结果与:
db.users.find({"name": /John/})
FullName类似于“last”,两个日期之间的状态==“结束”:
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==“待定”,orderId LIKE“PHA871674”:
db.orders.find({
status:"Pending",
orderId:/PHA876174/
}).pretty();