比较2个字段的MongoDB查询条件?
要查询比较2个字段的条件,请使用以下语法-
db.yourCollectionName.find( { $where: function() { returnthis.yourFirstFieldName为了理解语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> 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") }在find()方法的帮助下显示集合中的所有文档。查询如下:
> 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 }这是比较2个字段的条件查询-
> db.comparingTwoFieldsDemo.find( { $where: function() { returnthis.StudentMathMarks以下是输出-
{ "_id" : ObjectId("5c8ac0b46cea1f28b7aa0808"), "StudentName" : "Carol", "StudentAge" : 22, "StudentMathMarks" : 79, "StudentPhysicsMarks" : 89 } { "_id" : ObjectId("5c8ac0c96cea1f28b7aa0809"), "StudentName" : "David", "StudentAge" : 24, "StudentMathMarks" : 39, "StudentPhysicsMarks" : 45 }