Để truy vấn với điều kiện so sánh hai trường trong cùng một document, bạn sử dụng toán tử $where với hàm JavaScript.
Cú pháp
db.yourCollectionName.find( {
$where: function() {
return this.yourFirstFieldName < this.yourSecondFieldName
}
}).pretty();
Ví dụ minh họa
Tạo collection và dữ liệu
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"John","StudentAge":21,"StudentMathMarks":99,"StudentPhysicsMarks":98});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ac09e6cea1f28b7aa0807") }
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"Carol","StudentAge":22,"StudentMathMarks":79,"StudentPhysicsMarks":89});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ac0b46cea1f28b7aa0808") }
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"David","StudentAge":24,"StudentMathMarks":39,"StudentPhysicsMarks":45});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ac0c96cea1f28b7aa0809") }
> db.comparingTwoFieldsDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":87,"StudentPhysicsMarks":78});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ac0e06cea1f28b7aa080a") }
Xem tất cả documents
> db.comparingTwoFieldsDemo.find().pretty();
{
"_id" : ObjectId("5c8ac09e6cea1f28b7aa0807"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentMathMarks" : 99,
"StudentPhysicsMarks" : 98
}
{
"_id" : ObjectId("5c8ac0b46cea1f28b7aa0808"),
"StudentName" : "Carol",
"StudentAge" : 22,
"StudentMathMarks" : 79,
"StudentPhysicsMarks" : 89
}
{
"_id" : ObjectId("5c8ac0c96cea1f28b7aa0809"),
"StudentName" : "David",
"StudentAge" : 24,
"StudentMathMarks" : 39,
"StudentPhysicsMarks" : 45
}
{
"_id" : ObjectId("5c8ac0e06cea1f28b7aa080a"),
"StudentName" : "Bob",
"StudentAge" : 23,
"StudentMathMarks" : 87,
"StudentPhysicsMarks" : 78
}
Tìm student có điểm Toán < Vật lý
> db.comparingTwoFieldsDemo.find( {
$where: function() {
return this.StudentMathMarks < this.StudentPhysicsMarks
}
}).pretty();
{
"_id" : ObjectId("5c8ac0b46cea1f28b7aa0808"),
"StudentName" : "Carol",
"StudentAge" : 22,
"StudentMathMarks" : 79,
"StudentPhysicsMarks" : 89
}
{
"_id" : ObjectId("5c8ac0c96cea1f28b7aa0809"),
"StudentName" : "David",
"StudentAge" : 24,
"StudentMathMarks" : 39,
"StudentPhysicsMarks" : 45
}
Các phép so sánh khác
| Điều kiện | Code trong $where |
|---|---|
| Trường A > Trường B | return this.A > this.B |
| Trường A == Trường B | return this.A == this.B |
| Trường A != Trường B | return this.A != this.B |
| Trường A >= Trường B | return this.A >= this.B |
Cảnh báo hiệu năng: Toán tử
$where thực thi JavaScript cho từng document, rất chậm trên collection lớn. Chỉ dùng khi không thể dùng các toán tử query thông thường. Nên cân nhắc thiết kế schema để tránh so sánh cross-field.Thay thế tốt hơn (MongoDB 3.6+)
Sử dụng $expr với aggregation operators (hiệu năng tốt hơn $where):
db.comparingTwoFieldsDemo.find({
$expr: { $lt: ["$StudentMathMarks", "$StudentPhysicsMarks"] }
}).pretty();