mongo执行比较查询(字段之间的比较,当前前提是字段类型一致)

前端之家收集整理的这篇文章主要介绍了mongo执行比较查询(字段之间的比较,当前前提是字段类型一致)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

准备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 }

还可以实现按比较之后的差值进行排序

原文链接:https://www.f2er.com/note/422753.html

猜你在找的程序笔记相关文章