令人抓狂的代码 - MongoDB 区间查询

分享 未结
0 1 0 94
小编 2017-10-26发布
收藏 点赞

假设MongoDB有一张person表,数据如下:

{_id: 0, name: "tom",  age: 16}
{_id: 1, name: "jack", age: 17}
{_id: 2, name: "john", age: 18}
{_id: 3, name: "kary", age: 19}

我们需要查询年龄在18-20之间的记录,你可能会写出如下查询:

person.find({age: {$gte: 18}, age: {$lte: 20}})

然而返回结果并不是我们想要的:

{_id: 0, name: "tom",  age: 16}
{_id: 1, name: "jack", age: 17}
{_id: 2, name: "john", age: 18}
{_id: 3, name: "kary", age: 19}

原因是上面的查询其实等价于:

person.find({age: {$lte: 20}})

正确的写法应该是:

person.find({age: {$gte: 18, $lte: 20}})

这才是我们期望的返回结果:

{_id: 2, name: "john", age: 18}
{_id: 3, name: "kary", age: 19}



回帖
  • 消灭零回复