如何创建查询以查找 MongoDB 中字符串类型的 2 个数字之间的值
How to create a query that finds the values in between 2 numbers which are of type string in MongoDB
我实际上是 MongoDB 的新手,我需要创建一个 可以找到 10 到 500 之间的值的查询在 'quantity' 字段中。但是 'quantity' 的类型是 string .
下面的代码片段显示了我的库存模型(其中包含字符串类型的数量字段)
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 ] }
});
是的,因为$expr
一次支持一个表达式字段,您可以尝试这种方式,
Inventory.find({
$and:[
// GT FIRST
{$expr: { $gte: [ { $toDouble: "$quantity" }, 10.0 ] } },
// LT LAST
{$expr: { $lte: [ { $toDouble: "$quantity" }, 500.0 ]} }
]
});
有了$and我们可以使用2个独立的表达式
我实际上是 MongoDB 的新手,我需要创建一个 可以找到 10 到 500 之间的值的查询在 'quantity' 字段中。但是 'quantity' 的类型是 string .
下面的代码片段显示了我的库存模型(其中包含字符串类型的数量字段)
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 ] }
});
是的,因为$expr
一次支持一个表达式字段,您可以尝试这种方式,
Inventory.find({
$and:[
// GT FIRST
{$expr: { $gte: [ { $toDouble: "$quantity" }, 10.0 ] } },
// LT LAST
{$expr: { $lte: [ { $toDouble: "$quantity" }, 500.0 ]} }
]
});
有了$and我们可以使用2个独立的表达式