繁体   English   中英

在 MongoDB 查询中查找两个数字范围之间的所有记录

[英]Find All Records Between a Range of Two Numbers in a MongoDB Query

在 MongoDB 中有没有办法获取一系列数字之间的记录?

在我的示例中,我正在查找匹配common: 1的记录,并使用伪造的range() function 来仅获取该范围内的记录。 理论上,您可以只输入 function 范围内的任何数字,该范围内的记录将为 output。

这不是我要问的: $gte, $gt, $lte, $lt

注意:我不是基于值进行查询。 我正在根据文件系统中相对于所有其他记录的自然记录 position 进行查询。

用户收藏:

 db.users = [{ _id: 123, name: "Bill", common: 4 }, { _id: 456, name: "Jeff", common: 2 }, { _id: 789, name: "Steve", common: 4 }, { _id: 321, name: "Elon", common: 3 }, { _id: 654, name: "Larry", common: 1 }, ]

不工作的例子: (range() 不是真正的 function,只是用来提供一个想法)

 users.find({common: 4}).range(0, 2).then((users) => { console.log(users) })

预期结果:(因为公共字段匹配且记录在范围 0 和 2 之间)

 db.users = [{ _id: 123, name: "Bill", common: 4 }, { _id: 789, name: "Steve", common: 4 }, ]

这并没有给出确切的预期结果,但整个想法是在两个数字(例如一个范围)之间记录 select 条记录。 执行此操作的方法是使用 $skip 和 $limit 方法。

 users.aggregate([{$skip: 1}, {$limit: 3}, {$match: {common: 4}} ]).then((users) => { console.log(users) })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM