您可以使用$where运算符在MongoDB中比较字段值。首先让我们创建一个包含文档的集合
> db.comparingFieldDemo.insertOne({"Value1":30,"Value2":40}); { "acknowledged" : true, "insertedId" : ObjectId("5c9c99ed2d6669774125246e") } > db.comparingFieldDemo.insertOne({"Value1":60,"Value2":70}); { "acknowledged" : true, "insertedId" : ObjectId("5c9c99f62d6669774125246f") } > db.comparingFieldDemo.insertOne({"Value1":160,"Value2":190}); { "acknowledged" : true, "insertedId" : ObjectId("5c9c99ff2d66697741252470") } > db.comparingFieldDemo.insertOne({"Value1":200,"Value2":160}); { "acknowledged" : true, "insertedId" : ObjectId("5c9c9a0b2d66697741252471") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.comparingFieldDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9c99ed2d6669774125246e"), "Value1" : 30, "Value2" : 40 } { "_id" : ObjectId("5c9c99f62d6669774125246f"), "Value1" : 60, "Value2" : 70 } { "_id" : ObjectId("5c9c99ff2d66697741252470"), "Value1" : 160, "Value2" : 190 } { "_id" : ObjectId("5c9c9a0b2d66697741252471"), "Value1" : 200, "Value2" : 160 }
以下是通过比较字段值查找的查询。
> db.comparingFieldDemo.find({ $where: "this.Value1 > this.Value2" } );
这将产生以下输出
{ "_id" : ObjectId("5c9c9a0b2d66697741252471"), "Value1" : 200, "Value2" : 160 }
让我们看看另一个查询
> db.comparingFieldDemo.find({ $where: "this.Value1 < this.Value2" } );
这将产生以下输出
{ "_id" : ObjectId("5c9c99ed2d6669774125246e"), "Value1" : 30, "Value2" : 40 } { "_id" : ObjectId("5c9c99f62d6669774125246f"), "Value1" : 60, "Value2" : 70 } { "_id" : ObjectId("5c9c99ff2d66697741252470"), "Value1" : 160, "Value2" : 190 }