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

Truy vấn MongoDB tương tự toán tử LIKE trong SQL

MongoDB không có toán tử LIKE như SQL, nhưng hỗ trợ biểu thức chính quy (regex) để tìm kiếm mẫu chuỗi. Sử dụng cú pháp /mẫu/.

Tạo collection:

> db.demo26.insertOne({"StudentName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e14c9dc22d07d3b95082e79") }
> db.demo26.insertOne({"StudentName":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e14c9e022d07d3b95082e7a") }
> db.demo26.insertOne({"StudentName":"Jones"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e14ca7222d07d3b95082e7b") }
> db.demo26.insertOne({"StudentName":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e14ca7622d07d3b95082e7c") }

Xem dữ liệu:

> db.demo26.find();
{ "_id" : ObjectId("5e14c9dc22d07d3b95082e79"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e14c9e022d07d3b95082e7a"), "StudentName" : "John" }
{ "_id" : ObjectId("5e14ca7222d07d3b95082e7b"), "StudentName" : "Jones" }
{ "_id" : ObjectId("5e14ca7622d07d3b95082e7c"), "StudentName" : "David" }

Tìm tên chứa chuỗi "Jo" (tương đương LIKE '%Jo%'):

> db.demo26.find({"StudentName":/Jo/});

Kết quả:

{ "_id" : ObjectId("5e14c9e022d07d3b95082e7a"), "StudentName" : "John" }
{ "_id" : ObjectId("5e14ca7222d07d3b95082e7b"), "StudentName" : "Jones" }

Mở rộng: Có thể sử dụng các tùy chọn regex như /^Jo/ (bắt đầu bằng), /Jo$/ (kết thúc bằng), /Jo/i (không phân biệt chữ hoa/thường).