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

So sánh hai trường trong MongoDB với $where (JavaScript)

Toán tử $where cho phép dùng biểu thức JavaScript tùy ý trong query, bao gồm so sánh hai trường trong cùng tài liệu. Tuy mạnh mẽ nhưng chậm vì không dùng index, cần duyệt toàn bộ collection.

Dữ liệu mẫu

> db.demo7.insertOne({"FirstName1":"JOHN","FirstName2":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e0ccd1a25ddae1f53b6222f") }
> db.demo7.insertOne({"FirstName1":"Carol","FirstName2":"Mike"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e0ccd2725ddae1f53b62230") }
> db.demo7.insertOne({"FirstName1":"bob","FirstName2":"BOB"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e0ccd3225ddae1f53b62231") }

Xem dữ liệu

> db.demo7.find();
{ "_id" : ObjectId("5e0ccd1a25ddae1f53b6222f"), "FirstName1" : "JOHN", "FirstName2" : "John" }
{ "_id" : ObjectId("5e0ccd2725ddae1f53b62230"), "FirstName1" : "Carol", "FirstName2" : "Mike" }
{ "_id" : ObjectId("5e0ccd3225ddae1f53b62231"), "FirstName1" : "bob", "FirstName2" : "BOB" }

So sánh không phân biệt hoa/thường: FirstName1 == FirstName2

> db.demo7.find({$where: "this.FirstName1.toLowerCase() == this.FirstName2.toLowerCase()"});

Kết quả

{ "_id" : ObjectId("5e0ccd1a25ddae1f53b6222f"), "FirstName1" : "JOHN", "FirstName2" : "John" }
{ "_id" : ObjectId("5e0ccd3225ddae1f53b62231"), "FirstName1" : "bob", "FirstName2" : "BOB" }

Cảnh báo & Thay thế:

  • $where không sử dụng index, lock JavaScript engine, chậm, rủi ro bảo mật (injection).
  • Thay thế hiện đại (MongoDB 3.6+): Dùng $expr với aggregation operators trong query: { $expr: { $eq: [ { $toLower: "$FirstName1" }, { $toLower: "$FirstName2" } ] } }. $expr có thể dùng index (nếu đơn giản), an toàn và nhanh hơn.