【问题标题】:How to create a query that finds the values in between 2 numbers which are of type string in MongoDB如何创建一个查询来查找 2 个数字之间的值,这些数字是 MongoDB 中的字符串类型
【发布时间】:2020-11-14 00:35:20
【问题描述】:

我实际上是 MongoDB 的新手,我需要创建一个 可以在“数量”字段中找到介于 10 和 500 之间的值的查询。但是 'quantity' 是字符串类型。

下面的代码片段显示了我的库存模型(其中包含字符串类型的数量字段)

const inventorySchema = mongoose.Schema({
  email: {type: String , require:true},
  name: {type: String , require:true},
  quantity: {type: String , require:true}, //The quantity field is of type string
  batchId: {type: String , require:true},
  expireDate: {type: Date , require:true},
  price: {type: String , require:true},
  imagePath : { type: String , require: true}
}) 

我使用 $lte 和 $gte 操作使用了以下 mongoDB 表达式查询,但这不起作用。它给了我一个错误,说明“表示表达式的对象必须只有一个字段”

    const postQuery = Inventory.find({ $expr: { 
                                       $lte: [ { $toDouble: "$quantity" }, 500.0 ],
                                       $gte: [ { $toDouble: "$quantity" }, 10.0 ] }
                                     });

【问题讨论】:

    标签: database mongodb mongoose mongodb-query mean-stack


    【解决方案1】:

    可以,因为$expr一次支持一个表达式字段,你可以试试这种方式,

    Inventory.find({ 
        $and:[
        // GT FIRST
        {$expr: {  $gte: [ { $toDouble: "$quantity" }, 10.0 ] } },
        // LT LAST
        {$expr: { $lte: [ { $toDouble: "$quantity" }, 500.0 ]} }
        ]
    });
    

    使用 $and 我们可以使用 2 个单独的表达式

    【讨论】:

      猜你喜欢
      • 2014-05-25
      • 2014-10-11
      • 1970-01-01
      • 2015-03-22
      • 2010-12-15
      • 1970-01-01
      • 2015-10-12
      • 2013-05-27
      相关资源
      最近更新 更多