如何使用 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" }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP