Để truy vấn điều kiện so sánh 2 trường, hãy sử dụng cú pháp sau -
db.yourCollectionName.find( { $where: function() { return this.yourFirstFieldName < this.yourSecondFieldName } } ).pretty(); Để hiểu cú pháp, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -
> 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")
} Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau:
> db.comparingTwoFieldsDemo.find().pretty();
Sau đây là kết quả -
{
"_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
} Đây là truy vấn để điều kiện so sánh 2 trường -
> db.comparingTwoFieldsDemo.find( { $where: function() { return this.StudentMathMarks < this.StudentPhysicsMarks } } ).pretty(); Sau đây là kết quả -
{
"_id" : ObjectId("5c8ac0b46cea1f28b7aa0808"),
"StudentName" : "Carol",
"StudentAge" : 22,
"StudentMathMarks" : 79,
"StudentPhysicsMarks" : 89
}
{
"_id" : ObjectId("5c8ac0c96cea1f28b7aa0809"),
"StudentName" : "David",
"StudentAge" : 24,
"StudentMathMarks" : 39,
"StudentPhysicsMarks" : 45
}