MongoDB $gt/$lt operators with prices stored as strings

后端 未结 5 1305
一生所求
一生所求 2020-11-29 06:27

I\'m trying to query my database for prices greater than/less than a user specified number. In my database, prices are stored like so:

{price: \"300.00\"}
         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 07:20

    If you intend to use $gt with strings, you will have to use regex, which is not great in terms of performance. It is easier to just create a new field which holds the number value of price or change this field type to int/double. A javascript version should also work, like so:

    db.products.find("this.price > 30.00")
    

    as js will convert it to number before use. However, indexes won't work on this query.

提交回复
热议问题