MongoDB $gt/$lt 运算符,价格存储为字符串 [英] MongoDB $gt/$lt operators with prices stored as strings

查看:33
本文介绍了MongoDB $gt/$lt 运算符,价格存储为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的数据库中查询大于/小于用户指定数字的价格.在我的数据库中,价格是这样存储的:

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

根据文档,这应该有效:

According to the docs, this should work:

db.products.find({price: {$gt:30.00}}).pretty()

但是我没有返回任何结果.我也试过 {price: {$gt:30}}.

But I get no results returned. I've also tried {price: {$gt:30}}.

我在这里遗漏了什么?

是不是因为价格在数据库中存储为字符串而不是数字?有没有办法解决这个问题?

It it because the prices are stored as a string rather than a number in the DB? Is there a way around this?

推荐答案

如果您打算将 $gt 与字符串一起使用,您将不得不使用正则表达式,这在性能方面不是很好.只需创建一个包含价格数值的新字段或将此字段类型更改为 int/double 会更容易.javascript 版本也应该可以工作,如下所示:

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

因为 js 会在使用前将其转换为数字.但是,索引不适用于此查询.

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

这篇关于MongoDB $gt/$lt 运算符,价格存储为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆