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

Issue

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

Solution

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)
})

Answered By – twominds

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.