比较 2 个字段的 MongoDB 查询条件是什么?


若要查询比较 2 个字段的条件,请使用以下语法 −

db.yourCollectionName.find( { $where: function() { return this.yourFirstFieldName < this.yourSecondFieldName } } ).pretty();

为了理解此语法,我们创建一个文档集合。创建文档集合的查询如下 −

> 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() { 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
}

更新于: 30-Jul-2019

328 浏览

开启你的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.