Mongo db find operation query ($gte, $lt) is not working

Viewed 136

I had a problem using query with MongoDB. The problem was solved but I wanted to check if there was any other approach I could have taken.

At first, my model (Ad) had a property of price: {type: String}, and I tried to find by queries $gte and $lt to get ads with a price within a given range.

After reading online I figured that query operations are not working on String type properties.

Then even after changing the type to Number - price: {type: Number} - the find function didn't work properly on the price, even though on other properties which were type Number it worked as it should. In the end, I just deleted the whole database and reupload it, and then everything worked properly (haven't changed a thing). Has anyone had this kind of problem and solved it differently?

1 Answers

I'll first start by assuming you're using mongoose as the "types" you've pasted look like mongoose schema types.

You need to separate these two concepts:

  1. The schema that represents data at the app level
  2. The actual data in the DB.

Let's say I have this schema for a certain collection:

{ name: String }

But in the actual database there is only one document in that collection that looks like this:

{ price: 5, product_id: 1 }

Then when I query the data what do you expect to happen? do you expect mongoose to automatically generate a name for that document and delete the actual fields?

The reason it didn't "work" as you intended was that all the values were saved as string, changing the Schema does not retroactively update the database, so when you use $lt and $gte it uses string comparison which means "10" is less than "9" because that's how string comparison work.

The schema does help with newly inserted data and can cast it to the right type if supported, for that you should check the docs with what values are available.

Related