如何在MongoDB中使用$ regex?
以下是在MongoDB中使用$regex的语法-
db.yourCollectionName.find({yourFieldName: { $regex: yourValue}});首先让我们创建一个包含文档的集合-
> db.regularExpressionDemo.insertOne({"UserName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdffc25bf3115999ed51210")
}
> db.regularExpressionDemo.insertOne({"UserName":"JOHN"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdffc2ebf3115999ed51211")
}
> db.regularExpressionDemo.insertOne({"UserName":"john"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdffc35bf3115999ed51212")
}
> db.regularExpressionDemo.insertOne({"UserName":"JoHn"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdffc3ebf3115999ed51213")
}以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.regularExpressionDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }以下是使用$regex的查询-
> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN'}});这将产生以下输出-
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }现在让我们匹配所有情况。以下是查询-
> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN', $options: 'i' }});这将产生以下输出-
{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下