MongoDB 查询 (两个字段差值作为条件查询)

字段

  • name string
  • x int
  • y int

表记录

name x y
jhon 1 2
lily 2 1
gan 3 2

查询结果

查询所有 x > y 的所有 name

阅读 13.9k
2 个回答
db.collections.find({'$where': "this.x > this.y"}, {'name': 1})

这样还能按照x y 的差值排序

db.collection.aggregate(
    [  
      {
        $project : {
           _id: '$name',
           val: { $subtract : [ "$x", "$y" ] },
           x: '$x',
           y: '$y'
        }
      },
      {$match: {val: {$gt: 0}}},
      {$sort: { val: -1 }}
   ]
)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进