在 MongoDB 上查询时将 String 类型转换为 Number 类型

Convert String type to Number type when querying on MongoDB

我有一个这样的MongoDB结构。

[
  {
    _id: 1,
    data: [ 
      { price : "2", title: "title-1" }
    ]
  },
  {
    _id: 2,
    data: [ 
      { price : "2.0", title: "title-2" }
    ]
  },
  {
    _id: 3,
    data: [ 
      { price : "2.00", title: "title-3" },
      { price : "2.99", title: "title-4" }
    ]
  }

我想编写一个查询,我可以在其中输入所有价格值等于 2(数字类型)的标题。但问题是,价格字段是 String 类型。当我查询时,我必须为价格设置各种条件,例如:-

db.collection("test").find({ '$or': ["'data.price": '2'}, {"data.price": '2.0'}, {"data.price": '2.00'}] })

在 MongoDB 中有没有一种方法可以让我们说我们想要在查询之前转换类型?或者有没有办法可以更好地编写上述查询?

理想情况下,您应该验证集合的输入参数,以便保持数据类型一致,尤其是将数字数据保留为数字而不是字符串是有益的,

如果您想在查询之前转换现有项目,您需要使用 $map along with $toDouble。经过这样的转换后,您可以 运行 您的查询:

db.collection.aggregate([
    {
        $project: {
            data: {
                $map: {
                    input: "$data",
                    in: {
                        $mergeObjects: [
                            "$$this",
                            { price: { $toDouble: "$$this.price" } }
                        ]
                    }
                }
            }
        }
    },
    {
        $match: { "data.price": 2 }
    }
])

Mongo Playground