简体   繁体   English

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

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

Is there a way in MongoDB to get records between a range of numbers?在 MongoDB 中有没有办法获取一系列数字之间的记录?

In my example, I am finding the records that match common: 1 , and am using a fake range() function to get only the records between that range.在我的示例中,我正在查找匹配common: 1的记录,并使用伪造的range() function 来仅获取该范围内的记录。 In theory, you could just put any numbers in the range function and it would output the records in that range.理论上,您可以只输入 function 范围内的任何数字,该范围内的记录将为 output。

This is not what I am asking: $gte, $gt, $lte, $lt这不是我要问的: $gte, $gt, $lte, $lt

Note: I am not querying based on values.注意:我不是基于值进行查询。 I am querying based on the records natural position in the filesystem relative to all other records.我正在根据文件系统中相对于所有其他记录的自然记录 position 进行查询。

Users Collection:用户收藏:

 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 }, ]

Unworking Example: (range() isn't a real function, just used to give an idea)不工作的例子: (range() 不是真正的 function,只是用来提供一个想法)

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

Expected Result: (because the common fields match and the records are between the range 0 and 2)预期结果:(因为公共字段匹配且记录在范围 0 和 2 之间)

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

This doesn't give the exact expected result, but the whole idea was to select records between two numbers (eg. a range).这并没有给出确切的预期结果,但整个想法是在两个数字(例如一个范围)之间记录 select 条记录。 The way you do this is with the $skip and $limit methods.执行此操作的方法是使用 $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