Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách sử dụng $regex trong MongoDB

Cú pháp sử dụng $regex trong MongoDB:

db.tenCollectionCuaBan.find({ tenTruongCuaBan: { $regex: giaTriCuaBan } });

Tạo collection với document:

> 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") }

Hiển thị tất cả document:

> db.regularExpressionDemo.find();

Kết quả:

{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }

Truy vấn $regex khớp chính xác "JOHN" (phân biệt chữ hoa/thường):

> db.regularExpressionDemo.find({ 'UserName': { $regex: 'JOHN' } });

Kết quả:

{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }

Truy vấn $regex với option 'i' (case-insensitive) khớp tất cả biến thể:

> db.regularExpressionDemo.find({ 'UserName': { $regex: 'JOHN', $options: 'i' } });

Kết quả (trả về 4 document):

{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }