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

Biểu thức chính quy MongoDB khớp bản ghi cụ thể

Tạo collection với document:

> db.workingOfRegularExpressionDemo.insertOne({ "StudentDetails" : { "StudentName" : "John" }, "StudentAge": 21 });
{ "acknowledged" : true, "insertedId" : ObjectId("5cf227acb64a577be5a2bc07") }
> db.workingOfRegularExpressionDemo.insertOne({ "StudentDetails" : { "StudentName" : "JOHN" }, "StudentAge": 19 });
{ "acknowledged" : true, "insertedId" : ObjectId("5cf227b8b64a577be5a2bc08") }
> db.workingOfRegularExpressionDemo.insertOne({ "StudentDetails" : { "StudentName" : "Carol" }, "StudentAge": 20 });
{ "acknowledged" : true, "insertedId" : ObjectId("5cf227c2b64a577be5a2bc09") }

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

> db.workingOfRegularExpressionDemo.find();

Kết quả:

{ "_id" : ObjectId("5cf227acb64a577be5a2bc07"), "StudentDetails" : { "StudentName" : "John" }, "StudentAge" : 21 }
{ "_id" : ObjectId("5cf227b8b64a577be5a2bc08"), "StudentDetails" : { "StudentName" : "JOHN" }, "StudentAge" : 19 }
{ "_id" : ObjectId("5cf227c2b64a577be5a2bc09"), "StudentDetails" : { "StudentName" : "Carol" }, "StudentAge" : 20 }

Biểu thức chính quy tìm document có StudentName chính xác "JOHN" (phân biệt chữ hoa/thường):

> db.workingOfRegularExpressionDemo.find({'StudentDetails.StudentName': /JOHN/});

Kết quả:

{ "_id" : ObjectId("5cf227b8b64a577be5a2bc08"), "StudentDetails" : { "StudentName" : "JOHN" }, "StudentAge" : 19 }

Mẹo: Thêm option 'i' để không phân biệt chữ hoa/thường: {$regex: 'JOHN', $options: 'i'}.