您可以为此使用$cmp运算符。为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.matchBetweenFieldsDemo.insertOne({"FirstValue":40,"SecondValue":70}); { "acknowledged" : true, "insertedId" : ObjectId("5c92c9625259fcd19549980d") } > db.matchBetweenFieldsDemo.insertOne({"FirstValue":20,"SecondValue":5}); { "acknowledged" : true, "insertedId" : ObjectId("5c92c96b5259fcd19549980e") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.matchBetweenFieldsDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c92c9625259fcd19549980d"), "FirstValue" : 40, "SecondValue" : 70 } { "_id" : ObjectId("5c92c96b5259fcd19549980e"), "FirstValue" : 20, "SecondValue" : 5 }
这是聚合框架中字段之间$match的查询-
> db.matchBetweenFieldsDemo.aggregate([ ... {$project: { ... ... firstGreaterThanOrNot: {$cmp: ['$FirstValue', '$SecondValue']} ... }}, ... {$match: {firstGreaterThanOrNot:{$gt: 0}}} ... ]);
以下是输出-
{ "_id" : ObjectId("5c92c96b5259fcd19549980e"), "firstGreaterThanOrNot" : 1 }