简体   繁体   中英

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?

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. In theory, you could just put any numbers in the range function and it would output the records in that range.

This is not what I am asking: $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.

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)

 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)

 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). The way you do this is with the $skip and $limit methods.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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