准备mongo数据
db.test2.find().pretty()
{
"_id" : ObjectId("55ed2ad8f74ae739786cc781"),"name" : "zhangsan","x" : 1,"y" : 3
}
{
"_id" : ObjectId("55ed2ad9f74ae739786cc782"),"name" : "lisi","x" : 3,"y" : 2
}
{
"_id" : ObjectId("55ed2ad9f74ae739786cc783"),"name" : "wangwu","y" : 4
}
{
"_id" : ObjectId("55ed2adaf74ae739786cc784"),"name" : "zhaoliu","x" : 4,"y" : 1
}
> db.test2.find({'$where': "this.x > this.y"},{'name': 1})
{ "_id" : ObjectId("55ed2ad9f74ae739786cc782"),"name" : "lisi" }
{ "_id" : ObjectId("55ed2adaf74ae739786cc784"),"name" : "zhaoliu" }
mongo比较查询
这样可以简单的实现比较查询。还有一种比较查询的方式就是使用聚合查询,如下:
db.test2.aggregate([
... {
... $project : {
... "_id": "$name",... "val": { $subtract : [ "$x","$y" ] },... "x": "$x",... "y": "$y"
... }
... },... {$match:{val: {$gt: 0}}},... {$sort:{val: -1 }}
... ])
{ "_id" : "zhaoliu","y" : 1,"val" : 3 }
{ "_id" : "lisi","y" : 2,"val" : 1 }
还可以实现按比较之后的差值进行排序